import {Component, OnInit, ViewChild} from '@angular/core';
import {AlertController, NavController} from "@ionic/angular";
import {Router} from "@angular/router";
import { SessionDataProviderService } from 'src/app/store/session-data-provider.service';
import { BlogDataService } from 'src/app/store/blog-data.service';
import { WrenchService } from 'src/app/services/wrench.service';

@Component({
  selector: 'app-activetask',
  templateUrl: './activetask.page.html',
  styleUrls: ['./activetask.page.scss'],
})
export class ActivetaskPage implements OnInit {
  @ViewChild('yourmessage') yourmessage;
  tabs = 'about';
  status_description:string='';


  jobData: any;
  constructor(
      private navctr: NavController,
      private router: Router,
      public sessionDataProviderService: SessionDataProviderService,
      private alertController:AlertController,
      private wrenchService: WrenchService,
      public blogDataService: BlogDataService
  ) {

    this.jobData  =  this.router.getCurrentNavigation().extras.state;
    console.log("XXXXX 1",   this.router.getCurrentNavigation().extras);
    console.log("XXXXX 2",   this.router.getCurrentNavigation().extras.state);
    //console.log("XXXXX 3",   this.router.getCurrentNavigation().extras.state.ID);
    this.status_description =  this.jobData.status_description;
  }

  ngOnInit() {
    this.activeJobMsgList();
  }

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

/*
    sendTaskMessage(messageData){
        return this.getPostData("sendtaskmessage", messageData);
    }

    activeJobMsgList(contractData){
        return this.getPostData("activejobmsglist", contractData);
    }

      'member_id' => int 1
  'sessionid' => string '936571FD2E081B667930E7FFDF4D819938171883CA0CC951DC6C4FB184280EB3' (length=64)
  'uid' => string '3119b744-42ad-4834-bb83-b737588754ca' (length=36)
  'message' => string 'Lorem Ipsum comes from a latin text written in 45BC by Roman statesman, lawyer, scholar, and philosopher, Marcus Tullius Cicero' (length=127)
  'msg_type' => string 'TEXT' (length=4)
  'contract' => string '49BWBRW738' (length=10)
  'action' => int 14010
 */


  contrData: {
    action:number,
    member_id: number,
    uid: string,
    sessionid: string,
    limit:20,
    contract:string,
    offset: 0
  };
  msgListTotalData:any;
  msgListData: [];
  activeJobMsgList(){
    this.contrData = {
      action:14011,
      member_id: this.sessionDataProviderService.member_id,
      uid: this.sessionDataProviderService.member_uid,
      sessionid: this.sessionDataProviderService.session ,
      limit:20,
      contract: this.jobData.contract,
      offset: 0}

    this.wrenchService.activeJobMsgList(this.contrData).subscribe(
        msgListTotalData => {
          this.msgListTotalData = msgListTotalData;
          // console.log("REFER  RETURN->", this.referTotalData);
          this.msgListData = this.msgListTotalData.result_list;
          console.log("REFER RETURN DATA->", this.msgListData);
        }
    );

  }

  /*
        'member_id' => int 1
  'sessionid' => string '936571FD2E081B667930E7FFDF4D819938171883CA0CC951DC6C4FB184280EB3' (length=64)
  'uid' => string '3119b744-42ad-4834-bb83-b737588754ca' (length=36)
  'message' => string 'Lorem Ipsum comes from a latin text written in 45BC by Roman statesman, lawyer, scholar, and philosopher, Marcus Tullius Cicero' (length=127)
  'msg_type' => string 'TEXT' (length=4)
  'contract' => string '49BWBRW738' (length=10)
  'action' => int 14010
   */

  reqData: {
    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;
  sendActiveJobMessage(){
    if (this.yourmessage.length < 5){
      alert("Enter Message to send");
      return;
    }

    this.reqData = {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
    }

    this.wrenchService.sendTaskMessage(this.reqData).subscribe(
        reqResult => {
          this.msgReqResult = reqResult;
          console.log("msgReqResult  RETURN->", this.msgReqResult);
          this.interest_msg_status =  this.msgReqResult?.status;
          this.activeJobMsgList();
        }
    );
  }

  async taskCompleted(){
  //  alert(100);
    let reqData = {
      contract: this.jobData.contract,
      contract_uid: this.jobData.contract_uid,
      job_action: 'NOTIFY_COMPLETE',
    }

    const alert = await this.alertController.create({
      header: "Confirm the task is completed.",
      message: "The task owner will confirm the completion acceptance or rejection soon.",
      buttons: [
        {
          text: "Cancel",
          role: "cancel",
          handler: () => {
            // this.getMyOffersData();
          },
        },
        {
          text: "Confirm Completed ?",
          handler: () => {
// start
            // API CALL TO MARK TASK AS COMPLETED BY WORKER
            this.wrenchService.workerJobAction(reqData).subscribe((res)=> {
              if (res.status != 200 || res.data.internal_return < 0) {
                //  setReqStatus({loading:false, status: false, message: 'unable to complete request. Try again'})
               // Alert("Unable to set task as completed, try again soon");
              } else {
                this.router.navigate(['mytasks']);
              }
              }
            );
           // this.router.navigate(['mytasks']);
            // end
          },
        },
      ],
    });
    await alert.present();
}
  async taskCancel(){
    let reqData = {
      contract: this.jobData.contract,
      contract_uid: this.jobData.contract_uid,
      job_action: 'NOTIFY_CANCEL',
    }

    const alert = await this.alertController.create({
      header: "Confirm Cancel Request.",
      message: "The task owner will be informed of this cancellation. Once completed, we cannot reverse this action.",
      buttons: [
        {
          text: "Cancel",
          role: "cancel",
          handler: () => {
            // this.getMyOffersData();
          },
        },
        {
          text: "Confirm Cancel ?",
          handler: () => {
// start
            // API CALL TO MARK TASK AS COMPLETED BY WORKER
            this.wrenchService.workerJobAction(reqData).subscribe((res)=> {
                  if (res.status != 200 || res.data.internal_return < 0) {
                    //  setReqStatus({loading:false, status: false, message: 'unable to complete request. Try again'})
                    // Alert("Unable to set task as completed, try again soon");
                  } else {
                    this.router.navigate(['mytasks']);
                  }
                }
            );
            // this.router.navigate(['mytasks']);
            // end
          },
        },
      ],
    });
    await alert.present();
  }



}
