import {Component, OnInit, ViewChild} from '@angular/core';
import {AlertController, LoadingController, NavController} from "@ionic/angular";
import {Router} from "@angular/router";
import {SessionDataProviderService} from "../../store/session-data-provider.service";
import {WrenchService} from "../../services/wrench.service";
import {Camera, CameraResultType, CameraSource} from "@capacitor/camera";

@Component({
  selector: 'app-jobreview',
  templateUrl: './jobreview.page.html',
  styleUrls: ['./jobreview.page.scss'],
})
export class JobreviewPage implements OnInit {
  @ViewChild('yourmessage') yourmessage;
  jobData: any;
  tabs = 'message';
  item_banner:string = 'default.jpg';
  session_image_server:string='';
  curr_session:string='';
  constructor(
      private navctr: NavController,
      private router: Router,
      public sessionDataProviderService: SessionDataProviderService,
      private wrenchService: WrenchService,
      private alertController:AlertController,
      private loadingCtrl: LoadingController
  ) {
    this.jobData  =  this.router.getCurrentNavigation().extras.state;
    this.item_banner = this.jobData.banner;

    if ( this.jobData == undefined){
      this.onBack();
    }
  }


  ngOnInit() {
    this.curr_session =  this.sessionDataProviderService.session;
    this.session_image_server =  this.sessionDataProviderService.session_image_server;
    //this.activeJobMsgList();
  }

  onBack() {
    this.navctr.back();
  }

  async acceptCompletetion(){
    const alert = await this.alertController.create({
      header: "Approve Completion",
      message: "Confirm you are ready accept completion.",
      buttons: [
        {
          text: "Cancel",
          role: "cancel",
          handler: () => {
            // this.getMyOffersData();
          },
        },
        {
          text: "Approve",
          handler: () => {
            this.doJobAction("ACCEPT_COMPLETE");
            // this.sessionDataProviderService.DestroySessionOnLogout();
            // this.router.navigate(['logout']);
          },
        },
      ],
    });
    await alert.present();
  }

  async rejectCompletetion(){
    const alert = await this.alertController.create({
      header: "Reject Completion",
      message: "Confirm you are ready to reject completion.",
      buttons: [
        {
          text: "Cancel",
          role: "cancel",
          handler: () => {
            // this.getMyOffersData();
          },
        },
        {
          text: "Send Reject",
          handler: () => {
            this.doJobAction("REJECT_COMPLETE");
          },
        },
      ],
    });
    await alert.present();
  }

  response_result:string='';

  reqData: {
    action:number,
    member_id: number,
    uid: string,
    sessionid: string,
    contract:string,
    contract_uid:string,
    job_action:string
  };
  myFilesTotalData:any;
  doJobActionResponse:any;
/*
'sessionid' => '6AD58B08A9F458E6E6819DD603E202C657DB9BFFDD956C16386CC65975CE0D53,
'member_id' => 1,
'uid' => '3119b744-42ad-4834-bb83-b737588754ca',
'contract' => 'X2Y9WR5632',
'contract_uid' => '10654dc5-f574-4aa6-b8e6-93b95ac5fcec',
'job_action' => ‘ACCEPT_COMPLETE’,
'action' => 14015

 */
  async doJobAction(actionType){
    const loading = await this.loadingCtrl.create({
      message: 'Updating Status...',
      duration: 2500,
    });
    this.reqData = {
      action:14015,
      member_id: this.sessionDataProviderService.member_id,
      uid: this.sessionDataProviderService.member_uid,
      sessionid: this.sessionDataProviderService.session ,
      contract:this.jobData.contract,
      contract_uid:this.jobData.contract_uid,
      job_action:actionType
    };
    loading.present();
    this.wrenchService.activeJobStatus(this.reqData).subscribe(
        doJobActionResponse => {
          this.doJobActionResponse = doJobActionResponse;
          console.log("doJobAction  RETURN->", this.doJobActionResponse);
            if ( this.doJobActionResponse !=undefined && this.doJobActionResponse.result !=''){
             this.response_result = this.doJobActionResponse.result;
              setTimeout(async () => {
                this.response_result='';
                await this.onBack();
              }, 3000);
            }
        }
    );
  }
  // activeJobStatus(reqData){
  //   return this.getPostData("activejobstatus", reqData);
  // }


  reqMessageData: {
    action:number, member_id: number, uid: string, sessionid: string, msg_type:string,
    contract:string,
    message:string
  };

  interest_status:string = "";
  interest_msg_status:string = "";

  msgReqResult:any;
  async sendActiveJobMessage(){
    if (this.yourmessage == undefined || this.yourmessage?.length < 5){
      alert("Enter Message to send");
      return;
    }

    const loading = await this.loadingCtrl.create({
      message: 'Sending...',
      duration: 2500,
    });
    this.reqMessageData = {action:14010,
      member_id: this.sessionDataProviderService.member_id,
      uid: this.sessionDataProviderService.member_uid,
      sessionid: this.sessionDataProviderService.session ,
      msg_type: "TEXT",
      contract:this.jobData.contract,
      message: this.yourmessage
    }

    loading.present();
    this.wrenchService.sendTaskMessage(this.reqMessageData).subscribe(
        reqResult => {
          this.msgReqResult = reqResult;
          console.log("msgReqResult  RETURN->", this.msgReqResult);
          this.interest_msg_status =  this.msgReqResult?.status;
          //this.activeJobMsgList();
          const event = new Event("app-taskactivities-refresh");
          // Dispatch the event.
          dispatchEvent(event);

        }
    );
  }

  uploadData: {
    action:number,
    member_id: number,
    uid: string,
    contract: string,
    sessionid: string,
    msg_type:'FILE',
    file_name: string,
    file_size: number,
    file_type: string,
    file_data: string
  };

  uploadResult:any;
  async startCamera(cameraMode){
    const image = await Camera.getPhoto({
      quality: 50,
      width : 600,
      height : 300,
      allowEditing: false,
      resultType: CameraResultType.Base64,
      source: (cameraMode == 100 ) ? CameraSource.Camera  : CameraSource.Photos // Camera, Photos or Prompt!
    });

    if (image) {
      const loading = await this.loadingCtrl.create({
        message: 'Uploading updates',
        duration: 5000,
      });
      var file_size = parseInt(String(image.base64String.toString().length / 1.3224954) ) ;
      // this.saveImage(image)
      //debugger;
      //image.base64String
      this.uploadData={
        action:14010,
        member_id: this.sessionDataProviderService.member_id,
        uid: this.sessionDataProviderService.member_uid,
        contract: this.jobData.contract,
        sessionid: this.sessionDataProviderService.session ,
        msg_type:'FILE',
        file_name: `${this.jobData.contract}-job.${image.format}`,
        file_size: file_size ,
        file_type: `image/${image.format}`,
        file_data: image.base64String
      };
      //  console.log(this.uploadData);
      loading.present();
      this.wrenchService.uploadFile(this.uploadData).subscribe(
          uploadResult => {
            this.uploadResult = uploadResult;
            console.log("this.wrenchService.uploadFile RETURN DATA->", this.uploadResult);
            const event = new Event("app-taskactivities-refresh");
            // Dispatch the event.
            dispatchEvent(event);
          }
      );

      //  console.log( this.uploadData);
    }
  }
}
