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 { ToasterService } from '@service/toaster.service';
import { ConfirmpopComponent } from '../confirmpop/confirmpop.component';
declare var $:any;

// full-Calendar
// import { FullCalendarComponent, CalendarOptions } from '@fullcalendar/angular';

@Component({
  selector: 'app-viewclstrainingdetails',
  templateUrl: './viewclstrainingdetails.component.html',
  styleUrls: ['./viewclstrainingdetails.component.scss']
})
export class ViewClsTrainingComponent 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;
  typermdata: any=[];
  typeamdata: any=[];
  typedealerdata: any=[];
  typedsedata: any=[];
  typezmuserdata: any=[];
  typermuserdata: any=[];
  typeamuserdata: any=[];
  totalparticipant_list: any[];
  showdealer: boolean;
  showam: boolean;
  am_list: any=[];
  dealer_list: any=[];
  dse_list: any[];
  schedule_id: any;
  schedule_data: any;
  participant_list: any = [];
  reason:any;
  selectedtype: any;
  ques_id;
  ques_id_cancel;
  rolename: any;
  showmodify: boolean;
  reason_list: any;
  is_not_deleted_event: boolean = false;
  @ViewChild(ConfirmpopComponent) confirm_pop: ConfirmpopComponent;
  startdate;
  enddate;
  startTime;
  endTime;
  today=new Date();
  submitted: boolean;
  year = this.today.getFullYear();
  month = this.today.getMonth();
  day = this.today.getDate();
  options_start: DatepickerOptions = {
    minDate:  new Date(this.year,this.month,this.day) // Minimal selectable date
  }
  options_end: DatepickerOptions = {
    minDate:  new Date(this.year,this.month,this.day) // Minimal selectable date
  }
  is_startdate: boolean = true;
  is_enddate: boolean= true;
  is_starttime: boolean= true;
  is_endtime: boolean= true;
  currenttime: string;
  endtimes: any;
  showtext: boolean;
  fromtime: any;
  totime: any;
  trainingday: any;
  add_buttons: any = [];
  publish_status: any;
 
  constructor(private route: ActivatedRoute,public toaster : ToasterService,private formBuilder : FormBuilder ,private server: HyperService, private router: Router,private atp: AmazingTimePickerService,) { }

  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;

    LocalStorage.setValue('is_firsttime', false);
    this.registerForm = this.formBuilder.group({
      title: ['', Validators.required],
      trainer_level: ['', Validators.required],
      trainer_name: ['', Validators.required],
      startdate: [new Date(),Validators.required],
     // enddate : [new Date(),Validators.required],
      startTime : ['',Validators.required],
      endTime : ['',Validators.required]
    });
  
  }

  backclicked(){
    this.router.navigateByUrl('trainer');
  }

  getreasondata(){
    this.server.get("crtraining/cancelreschedulelist").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('');
      }
    })
  }

  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_not_deleted_event = this.schedule_data.is_deleted == 0 ? true : false;
        // if(!this.is_not_deleted_event){
        //   let msg2 = "Training is Deleted";
        //   this.confirm_pop.confirmPopups(msg2, (data) => {
        //     this.router.navigateByUrl('trainer');
        //   }, (data)=>{
        //     this.router.navigateByUrl('trainer');
        //   })        
        // }
        this.participant_list = this.schedule_data.participant;
        let given_date = new Date(new Date(this.schedule_data.start_date).getTime() - 1 * 24 * 60 * 60 * 1000);
        let today = new Date();
        this.startdate = moment(this.schedule_data.start_date).format("YYYY-MM-DD");
        this.enddate = moment(this.schedule_data.end_date).format("YYYY-MM-DD");
        this.startTime = this.schedule_data.starttime;
        this.endTime = this.schedule_data.endtime;
        // this.showmodify = given_date >= today ?true : false;
        this.showmodify = this.schedule_data.training_update_status;
        this.publish_status = this.schedule_data.status;
        // alert(this.publish_status)
        try {
          this.fromtime = JSON.parse(this.schedule_data.starttime)
        } catch (e) {
          this.fromtime = this.schedule_data.starttime
        }
        try {
          this.totime = JSON.parse(this.schedule_data.endtime)
        } catch (e) {
          this.totime = this.schedule_data.endtime
        }
        // this.fromtime = JSON.parse(this.schedule_data.starttime)
        // this.totime = JSON.parse(this.schedule_data.endtime)
        this.trainingday = this.schedule_data.training_days;
        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(this.fromtime.length!=0){
          for (let i = 0; i <  this.trainingday; i++) {
            this.add_buttons.push({
              'id' : i,
              'day' : 'Day'+' '+ (i+1),
              'from' : this.fromtime[i],
              'to' : this.totime[i],
              'date' : between[i]
            });
          }
        }else{
          for (let i = 0; i <  this.trainingday; i++) {
            this.add_buttons.push({
              'id' : i,
              'day' : 'Day'+' '+ (i+1),
              'from' : this.fromtime,
              'to' : this.totime,
              'date' : between[i]
            });
          }
        }
      } else if (data.result.response == "failed" && data.status == 401) {
        this.router.navigateByUrl('');
      }
    })
  }

  changestartdate(tempvalue){
    this.options_end={
      minDate: new Date(tempvalue)
    }
    this.enddate=tempvalue;
  }
  //=
  changeenddate(tempvalue){
   
  }

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

  validate(){
    this.is_startdate = (this.startdate != '' && this.startdate != undefined) ? true : false;
    this.is_enddate = (this.enddate != '' && this.enddate != undefined) ? true : false;
    this.is_starttime = (this.startTime != '' && this.startTime != undefined) ? true : false;
    this.is_endtime = (this.endTime != '' && this.endTime != undefined) ? true : false;
    return (this.startdate!=''&& this.startdate != undefined && this.enddate != '' && this.enddate != undefined && this.startTime != '' && this.startTime != undefined && this.endTime != '' && this.endTime != undefined)
  }

  openstartclock(){
    var today_date = this.today.getFullYear()+'/'+this.today.getMonth()+'/'+this.today.getDate();
    var date = this.registerForm.controls['startdate'].value;
    let year = moment(date).format("YYYY");
    let month = moment(date).format("MM");
    let day = moment(date).format("DD");
    var selected_date = year+'/'+month+'/'+day
    if(selected_date > today_date){
      this.currenttime = '00:00'
    }else{
      this.currenttime = new Date().getHours()+':'+new Date().getMinutes();
    }
    const amazingTimePicker = this.atp.open({
      time:  this.currenttime,
      rangeTime: { start: this.currenttime, end: this.endtimes },
      arrowStyle: {
          background: 'red',
          color: 'white'
      }
    });
      amazingTimePicker.afterClose().subscribe(time => {
        this.startTime = time;

    });
    this.endTime = '';
  }

  openendclock(){
    if(this.startTime!=null && this.startTime!='' && this.startTime!=undefined){
       let a : any =this.startTime.split(':');
       let b = Number(a[1])+Number(5);
       let min;
       let correct_time;
       if(b>=60){
        a[0] = Number(a[0])+Number(1);
        min = b - Number(60);
        correct_time = a[0]+':'+min;
       }else{
        min = b;
        correct_time = a[0]+':'+min;
       }
      const amazingTimePicker = this.atp.open({
        time:  correct_time,
        rangeTime: { start: correct_time, end: this.endtimes },
        arrowStyle: {
            background: 'red',
            color: 'white'
        }
      });
        amazingTimePicker.afterClose().subscribe(time => {
          this.endTime = time;
      });
    }else{
      this.toaster.show('Please select start time');
      // alert('Please select start time')
    }
  }

  public oncancel(){
    this.router.navigateByUrl('trainer');
  }

  dataradio(e){
    this.showtext = false;
    this.ques_id = '';
    this.ques_id_cancel = '';
  }

  modifydata(id){
    // this.router.navigateByUrl('editclstraining/'+id)
    this.router.navigateByUrl('newedittraining/'+id)
  }

  public onSubmit(){
    var start =(moment(this.schedule_data.start_date).format('DD-MM-YYYY HH:mm:ss')).split(' ');
    var end =(moment(this.schedule_data.end_date).format('DD-MM-YYYY HH:mm:ss')).split(' ');
    if(this.reason == 'cancel'){
      if(this.ques_id_cancel != null && this.ques_id_cancel != '' && this.ques_id_cancel != undefined){
        this.loader = true;
        this.server.get('crtraining/canceltraining/'+this.schedule_id+'/'+this.ques_id_cancel).then((res)=>{
          this.loader = false;
          if (res.status == 200 && res.result.response == "success") {
            this.router.navigateByUrl('trainer');
          }else{
            // alert(res.result.message);
            this.router.navigateByUrl('trainer');
          }
        })
      }else{
        this.toaster.show('Please select reason for Cancel');
      }
     
    }else if(this.reason == 'reschedule'){
      if(this.ques_id != null && this.ques_id != '' && this.ques_id != undefined){
        if(this.validate()){
          this.loader = true;
          this.server.post('crtraining/rescheduletraining/'+this.schedule_id+'/'+this.ques_id,{
            'startdate' : this.startdate,
            'enddate' : this.enddate,
            'starttime' : this.startTime,
            'endtime' : this.endTime
          }).then((res)=>{
            this.loader = false;
            if (res.status == 200 && res.result.response == "success") {
              this.router.navigateByUrl('trainer');
            }else if (res.result.response == "failed" && res.status == 401) {
              this.router.navigateByUrl('');
            }else{
              // alert(res.result.message);
              this.router.navigateByUrl('trainer');
            }
          })
        }else{
        }
      }else{
        this.toaster.show('Please select reason for Reschedule');
      }
    }else{
      this.toaster.show('Please select Cancel or Reschedule option');
    }
    // https://hyper-m.cygnusa.in/_api/web/en_us/crtraining/rescheduletraining/<TRAINING ID>/<QUESTION ID>
    //  https://hyper-m.cygnusa.in/_api/web/en_us/crtraining/canceltraining/<TRAINING 
  }

  cancelmodal(){
    $('#publish-modal').modal('hide');
  }

  onpublish(){
    $('#publish-modal').modal('hide');
    let dse = [];
    this.participant_list.forEach(function(data) {
      dse.push(data.userid)
    });
    let sendreq_params = {
      "title" : this.schedule_data.lvl_id,
      "description" : this.schedule_data.schedule_name,
      "startdate" : this.schedule_data.startdate,
      "enddate" : this.schedule_data.enddate,
      "starttime" : this.schedule_data.starttime,
      "endtime" : this.schedule_data.endtime,
      "is_feedback":this.schedule_data.is_feedback,
      "venue_type": this.schedule_data.venue_type,
      "venue_dealer": this.schedule_data.venue_dealer ,
      "venue_address" : this.schedule_data.venue_address,
      "assessments" : JSON.stringify(this.schedule_data.assessment),
      "dse" : JSON.stringify(dse),
      "venue_am" : this.schedule_data.venue_am,
      "adhoc_training" : this.schedule_data.adhoc_training,
      "business_segment" : this.schedule_data.business_segment,
      "training_other_title" : this.schedule_data.training_other_title,
      "date_restriction" : this.schedule_data.date_restriction,
      "status" : 1,
      "filter_zone" : this.schedule_data.zone,
      "training_total_hours" : this.schedule_data.training_total_hours,
      "schedule_id" : this.schedule_id,
    }
    this.loader = true;
    this.server.post("crtraining/updatetraining",sendreq_params
    ).then((data) => {
      this.loader = false;
      if (data.status == 200 && data.result.response == "success") {
        let msg2 = "Training Published successfully";
        this.confirm_pop.confirmPopups(msg2, (data) => {
          this.router.navigateByUrl('trainer');
        }, (data)=>{
          this.router.navigateByUrl('trainer');
        })
      }else if(data.status == 406 && data.result.response == "failed"){
        this.confirm_pop.confirmPopups(data.result.message, (data) => {
        }, (data)=>{
        })
      }else{
        this.router.navigateByUrl('');
      }
    })

  }

}
