import { Component, OnInit, ViewChild } from '@angular/core';
import { HyperService } from '../../core/services/http.service';
import { Router } from '@angular/router';
import { ActivatedRoute } from '@angular/router';
import { LocalStorage } from '../../core/services/local_storage.service';
import * as moment from 'moment';
import { DatepickerOptions } from 'ng2-datepicker';
import { AmazingTimePickerService } from 'amazing-time-picker';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { Location } from '@angular/common';
declare var $: any;

@Component({
  selector: 'app-trainingnotification',
  templateUrl: './trainingnotification.component.html',
  styleUrls: ['./trainingnotification.component.scss']
})
export class TrainingNotificationComponent implements OnInit {
  loader: boolean;
  trainer_welcomenote = '';
  trainer_error: string = '';
  itemdetail = [];
  is_filter: boolean = true;
  filter_year: any;
  filter_month: any;
  filter_date: any;
  selected_type: any = 1;
  date_now:any;
  times = {
    year: 31557600,
    month: 2629746,
    day: 86400,
    hr: 3600,
    min: 60,
    sec: 1
  }
  sub: any;
  type: any;
  user_id: any;
  userData: any = {};
  setMenuId:string;
  videoitemdetail: any;
  batchitemdetail: any;
  registerForm: FormGroup;
  // calendarOptions: CalendarOptions = {
  //   initialView: 'dayGridMonth'
  // };
  options: DatepickerOptions = {
    minDate: new Date(Date.now()), // Minimal selectable date
    maxDate: new Date(Date.now()),  // Maximal selectable date
  };
  rm_list: any = [];
  showdse: boolean;

  reason;
  selectedtype: any;
  ques_id;
  ques_id_cancel;
  rolename: any;
  showmodify: boolean;
  schedule_id: any;
  schedule_data: any = [];
  Dsedata:any;
  showerror: boolean;
  response: any;
  reason_list: any;
  showtext: boolean;
  other_reason:any;
  showtemperror: boolean;
  add_date_buttons: any=[];
  dsedetails: any;
  is_deleted: any;
  constructor(private route: ActivatedRoute,private formBuilder : FormBuilder ,private server: HyperService, private router: Router,private atp: AmazingTimePickerService,public _location : Location) { }

  ngOnInit(){
    this.route.params.subscribe(params => {
      let temp = params['id'];
      this.schedule_id = temp;
    });

    this.getdetails();
    this.getreasondata();
    this.rolename = LocalStorage.getValue('user_data').role;

  }

  getreasondata(){
    this.server.get("crtraining/declinetrainingreasonlist").then((data) => {
      if (data.status == 200 && data.result.response == "success") {
        this.reason_list= data.result.data;
      }else if (data.result.response == "failed" && data.status == 401) {
        this.router.navigateByUrl('');
      }
    })
  }

  selectreason(e){
    this.showerror = false;
    this.showtext = e.target.value == 6 ? true : false;
  }

  oncancel(){
    this.showerror = false;
    this.showtext = false;
    this.reason = '';
    this.other_reason = '';
    this.showtemperror = false;
  }

  backclicked(){
    this._location.back();
  }

  attendance_absent(){
    if(this.reason != undefined && this.reason !=null && this.reason != ''){
      if(this.showtext){
        if(this.other_reason != undefined && this.other_reason !=null && this.other_reason != ''){
          this.showtemperror = false;
          this.showtext = false;
          $('#declinemodal').modal('hide');
          this.amresponse(this.dsedetails.userid,this.response,'');
          // this.other_reason = '';
          // this.reason = '';
        }else{
          this.showtemperror = true;
        }
      }else{  
        this.showerror = false;
        this.showtext = false;
        $('#declinemodal').modal('hide');
        this.amresponse(this.dsedetails.userid,this.response,'');
        // this.reason = '';
      }
    }else{
      this.showerror = true;
    }
  }

  clickdecline(data,res){
    this.dsedetails = data;
    this.response = res;
  }

  amresponse(userid,data,role){
    let senddata = {};
    if(data == 1){
      if(role == 'dse'){
        senddata = {
          "schedule_id" : this.schedule_id,
          "userid" : userid,
          "status" : data,
          "decline_reason" : '',
          "decline_reason_desc" : '',
          "acknowledge_by" : 2
        }
      }else{
        senddata = {
          "schedule_id" : this.schedule_id,
          "userid" : userid,
          "status" : data,
          "decline_reason" : '',
          "decline_reason_desc" : '',
          "acknowledge_by" : 1
        }
      }
      
    }else{
      senddata = {
        "schedule_id" : this.schedule_id,
        "userid" : userid,
        "status" : data,
        "decline_reason" : this.reason,
        "decline_reason_desc" : this.other_reason,
        "acknowledge_by" : 1
      }
    }
    if(!this.schedule_data.training_completed){
      this.loader = true;
      this.server.post("crtraining/acceptdeclinetraining",senddata).then((data) => {
        this.loader = false;
        if (data.status == 200 && data.result.response == "success") {
          this.reason = '';
          this.other_reason = '';
          this.getdetails();
        } else if (data.result.response == "failed" && data.status == 401) {
          this.router.navigateByUrl('');
        }
      })
    }
  }


  amreject(userid){

  }

  getdetails(){
    this.loader = true; 
    this.server.get("crtraining/"+this.schedule_id).then((data) => {
      this.loader = false;
      if (data.status == 200 && data.result.response == "success") {
        this.schedule_data= data.result.data[0];
        this.is_deleted = this.schedule_data.is_deleted;
        if(this.schedule_data.participant!=''&&this.schedule_data.participant!=undefined&&this.schedule_data.participant!=null){
          for(let i=0;i<this.schedule_data.participant.length;i++){
            if(LocalStorage.getValue('user_data').smpin == this.schedule_data.participant[i].smpin){
              this.Dsedata = this.schedule_data.participant[i];
            }
          }
        }
        let fromtime;
        let totime;
        try {
          fromtime = JSON.parse(this.schedule_data.starttime)
        } catch (e) {
          fromtime = this.schedule_data.starttime
        }
        try {
          totime = JSON.parse(this.schedule_data.endtime)
        } catch (e) {
          totime = this.schedule_data.endtime
        }
        // let fromtime = JSON.parse(this.schedule_data.starttime)
        // let totime = JSON.parse(this.schedule_data.endtime)
        this.add_date_buttons = [];
        var currentDate = new Date(this.schedule_data.startdate);
        var between = [];
        while (currentDate <=new Date(this.schedule_data.enddate)) {
          between.push(moment(currentDate).format('MMM DD, YYYY'));
          currentDate.setDate(currentDate.getDate() + 1);
        }
        if(fromtime.length!=0){
          for (let i = 0; i <  between.length; i++) {
            this.add_date_buttons.push({
              'id' : i,
              'day' : 'Day'+' '+ (i+1),
              'date' : between[i]+' '+fromtime[i]+', '+totime[i]
            });
          }
        }else{
          for (let i = 0; i <  between.length; i++) {
            this.add_date_buttons.push({
              'id' : i,
              'day' : 'Day'+' '+ (i+1),
              'date' : between[i]+' '+fromtime+', '+totime
            });
          }
        }
        let given_date = new Date(new Date(this.schedule_data.start_date).getTime() - 3 * 24 * 60 * 60 * 1000);
        let today = new Date();
        this.showmodify = given_date >= today ?true : false;
      } else if (data.result.response == "failed" && data.status == 401) {
        this.router.navigateByUrl('');
      }
    })
  }

  // openreasontip(){
  //   $('.popover-inn').css("opacity",1)
  // }

  // clickresponse(){
  //   if(!this.schedule_data.training_completed){
  //     this.loader = true;
  //     this.server.get("crtraining/acceptdeclinetraining/"+this.schedule_id+'/'+this.schedule_data.userid+'/1').then((data) => {
  //       this.loader = false;
  //       if (data.status == 200 && data.result.response == "success") {
  //       this.getdetails();
  //       } else if (data.result.response == "failed" && data.status == 401) {
  //         this.router.navigateByUrl('');
  //       }
  //     })
  //   }
  // }
}
