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

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

@Component({
  selector: 'app-addclstraining',
  templateUrl: './addclstraining.component.html',
  styleUrls: ['./addclstraining.component.scss']
})
export class AddClsTrainingComponent 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'
  // };
  @ViewChild(ConfirmpopComponent) confirm_pop: ConfirmpopComponent;
  today=new Date();
  submitted: boolean;
  year = this.today.getFullYear();
  month = this.today.getMonth();
  day = this.today.getDate();
  // mindate:any = moment({year: this.year, month: this.month, day: this.day}).format('YYYY-MM-DD');
  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
  }
  rm_list: any = [];
  showdse: boolean;
  typermdata: any=[];
  typeamdata: any=[];
  typedealerdata: any=[];
  typedsedata: any=[];
  typezmuserdata: any=[];
  typermuserdata: any=[];
  typeamuserdata: any=[];
  totalparticipant_list = [];
  showdealer: boolean;
  showam: boolean;
  am_list: any=[];
  dealer_list: any=[];
  dse_list: any[];
  showcomment: boolean = false;
  showdealerdrop: boolean = false;
  level_list: any;
  currenttime: string;
  endtimes: any;
  startTime: any;
  endTime: any;
  public min = new Date();
  zoneam_list: any;
  zonedealer_list: any;
  correcttime = new Date().getHours()+':'+new Date().getMinutes();
  venue_address: any;
  enddate: string;
  constructor(private route: ActivatedRoute,private toaster: ToasterService,private _location: Location,private formBuilder : FormBuilder ,private server: HyperService, private router: Router,private atp: AmazingTimePickerService,) { }

  ngOnInit() {
    LocalStorage.setValue('is_firsttime', false);
    this.getbaselevel();
    this.getRmlist();

    this.registerForm = this.formBuilder.group({
      title: ['', Validators.required],
      description: ['', Validators.required],
      startdate: [new Date(),Validators.required],
      enddate : [new Date(),Validators.required],
      startTime : ['',Validators.required],
      endTime : ['',Validators.required],
      venue_type : ['',Validators.required],
      venue_dealer : [''],
      venue_am : [''],
      venue_address : ['', Validators.required],
      is_feedback : [''],
      assessnamepre : [''],
      assessquescountpre : [''],
      assessTimepre : [''],
      assessnamepost : [''],
      assessquescountpost : [''],
      assessTimepost : ['']
    });
  
  }

  changetitle(e){
    this.showam = false;
    this.showdealer = false;
    this.showdse = false;
    this.totalparticipant_list = [];
    this.getRmlist();
  }

  openstartclock(){
    var today_date = this.today.getFullYear()+'/'+this.today.getMonth()+'/'+this.today.getDate();
    var date = this.registerForm.controls['startdate'].value;
    var selected_date = date.getFullYear()+'/'+date.getMonth()+'/'+date.getDate()
    if(new Date(selected_date) > new 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 => {
        let times:any = time.split(':');
        let amorpm = times[0] >= 12 ? 'PM' : 'AM';
        times[0] = (times[0] % 12) || 12;
        let final = times[0]+':'+times[1]+' '+amorpm;
        // alert(moment(time, ["HH:MM"]).format("hh:mm A"));
        this.startTime = time;
        this.registerForm.controls['startTime'].setValue(this.startTime)
    });
    this.registerForm.controls['endTime'].setValue('');
  }

  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;
          this.registerForm.controls['endTime'].setValue(this.endTime)
      });
    }else{
      this.toaster.show('Please select start time');
    }
  }

  changestartdate(tempvalue){
    this.enddate = '';
    this.registerForm.controls['enddate'].setValue(tempvalue);
    this.options_end={
      minDate: new Date(tempvalue)
    }
  }
 
  changeenddate(tempvalue){
    // if((this.startdate=='')||(this.startdate==undefined)){
    //   this.enddate='';
    //  // return false;
    // }else{

    // }
  }

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

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

  getRmlist(){
    this.server.post("common/trainerrm",'')
    .then((data) => {
      if (data.status == 200 && data.result.response != 'failed'){
        this.rm_list = data.result.data;
      }
    })
  }
  
  getbaselevel(){
    this.server.get("crtraining/baselevel").then((data) => {
      this.loader = false;
      if (data.status == 200 && data.result.response == "success") {
        this.level_list = data.result.data;
      } else if (data.result.response == "failed" && data.status == 401) {
        this.router.navigateByUrl('');
      }
    })
  }

  Changerm(event,i){
    this.typeamdata = [];
    this.typedealerdata = [];
    this.typedsedata = [];
    this.totalparticipant_list = [];
    this.showdealer = false;
    this.showdse = false;
    var value=event.target.value;
    var senddata={};
    const index = this.typermdata.indexOf(value);
    if(event.target.checked){
      this.typermdata.push(event.target.value);
    }else{
      if (index > -1) {
        this.typermdata.splice(index, 1);
      }
    }
    senddata = {"rm_email":JSON.stringify(this.typermdata)}
    this.server.post("common/traineram",senddata)
    .then((data) => {
      if (data.status == 200 && data.result.response != 'failed'){
        this.showam = true;
        this.am_list = data.result.data;
        // this.participant_data = data.result.data.participant;
      }else{
        this.am_list=[];
        this.showam =false;
        this.showdealer =false;
        this.showdse =false;
      }
  })
  }
  Changeam(event,i){
    this.typedealerdata = [];
    this.typedsedata = [];
    this.totalparticipant_list =[];
    this.showdse = false;
    var value=event.target.value;
    var senddata={};
    const index = this.typeamdata.indexOf(value);
    if(event.target.checked){
      this.typeamdata.push(event.target.value);
    }else{
      if (index > -1) {
        this.showdealer = false;
        this.typeamdata.splice(index, 1);
      }
    }
    senddata = {"am_email":JSON.stringify(this.typeamdata)}
    this.server.post("common/trainerdealer",senddata)
    .then((data) => {
      if (data.status == 200 && data.result.response != 'failed'){
        this.showdealer = true;
        this.dealer_list = data.result.data;
        // this.participant_data = data.result.data.participant;
      }else{
        this.dealer_list=[];
        this.showdealer =false;
        this.showdse =false;
      }
  })
  }
  Changedealer(event,i){
    this.typedsedata = [];
    this.totalparticipant_list = [];
    var value=event.target.value;
    var senddata={};
    const index = this.typedealerdata.indexOf(value);
    if(event.target.checked){
      this.typedealerdata.push(event.target.value);
    }else{
      if (index > -1) {
        this.showdse =false;
        this.typedealerdata.splice(index, 1);
      }
    }
    senddata = {"dealer_code":JSON.stringify(this.typedealerdata)}
    this.server.post("common/dselist",senddata)
    .then((data) => {
      if (data.status == 200 && data.result.response != 'failed'){
        this.showdse = true;
        this.dse_list = data.result.data;
        // this.participant_data = data.result.data.participant;
      }else{
        this.dse_list=[];
        this.typedsedata=[];
        this.showdse =false;
      }
  })
  }
  Changedse(event){
    this.totalparticipant_list =[];
    var value=event.target.value;
    const index = this.typedsedata.indexOf(value);
    if(event.target.checked){
      this.typedsedata.push(event.target.value);
      this.displaylist(this.typedsedata);
    }else{
      if (index > -1) {
        this.typedsedata.splice(index, 1);
        this.displaylist(this.typedsedata);
      }
    }
  }

  displaylist(data){
    this.totalparticipant_list=[];
    for(let i=0;i<this.dse_list.length;i++){
      for(let j=0;j<data.length;j++){
        if(this.dse_list[i].userid==data[j]){
          this.totalparticipant_list.push(this.dse_list[i]);
        }
      }
    }
  }

  selectvenuetype(e){
    this.registerForm.controls['venue_dealer'].setValue('');
    this.registerForm.controls['venue_am'].setValue('');
    if(e.target.value == '1'){
      this.showcomment = false;
      this.showdealerdrop = true;
      this.getam();
      this.registerForm.controls['venue_address'].setValue('');
    }else if(e.target.value == '2'){
      this.showdealerdrop = false;
      this.showcomment = true;
      this.registerForm.controls['venue_address'].setValue('');
    }
  }

  getam(){
    this.registerForm.controls['venue_address'].setValue('');
    this.server.get("common/trainerzoneam").then((data) => {
      this.loader = false;
      if (data.status == 200 && data.result.response == "success") {
        this.zoneam_list = data.result.data;
      } 
      else if (data.result.response == "failed") {
      }
    })
  }

  changearea(e){
    let obj =[];
    obj.push(e.target.value);
    this.registerForm.controls['venue_address'].setValue('');
    this.server.post("common/trainerdealer", { 'am_email' : JSON.stringify(obj) }).then((data) => {
      this.loader = false;
      if (data.status == 200 && data.result.response == "success") {
        this.zonedealer_list = data.result.data;
      } 
      else if (data.result.response == "failed" && data.status == 406) {
      }
    })
  }

  selectdealer(e){
    for(let i=0;i<this.zonedealer_list.length;i++){
      if(e.target.value == this.zonedealer_list[i].dealer_code){
        this.venue_address = this.zonedealer_list[i].address; 
      }
    }
    if(this.venue_address != '' && this.venue_address != null && this.venue_address != undefined){
      this.registerForm.controls['venue_address'].setValue(this.venue_address) 
    }else{
      this.registerForm.controls['venue_address'].setValue('No address') 
    }
  }

  getvalue(e){
    if(e.target.checked){
      if(e.target.value == 1){
        this.registerForm.controls['assessnamepre'].setValidators([Validators.required]);
        this.registerForm.controls['assessnamepre'].updateValueAndValidity();
        this.registerForm.controls['assessquescountpre'].setValidators([Validators.required]);
        this.registerForm.controls['assessquescountpre'].updateValueAndValidity();
        this.registerForm.controls['assessTimepre'].setValidators([Validators.required]);
        this.registerForm.controls['assessTimepre'].updateValueAndValidity();
      }else if(e.target.value == 2){
        this.registerForm.controls['assessnamepost'].setValidators([Validators.required]);
        this.registerForm.controls['assessnamepost'].updateValueAndValidity();
        this.registerForm.controls['assessquescountpost'].setValidators([Validators.required]);
        this.registerForm.controls['assessquescountpost'].updateValueAndValidity();
        this.registerForm.controls['assessTimepost'].setValidators([Validators.required]);
        this.registerForm.controls['assessTimepost'].updateValueAndValidity();
      }
    }else{
      if(e.target.value == 1){
        this.registerForm.controls['assessnamepre'].clearValidators();
        this.registerForm.controls['assessnamepre'].updateValueAndValidity();
        this.registerForm.controls['assessquescountpre'].clearValidators();
        this.registerForm.controls['assessquescountpre'].updateValueAndValidity();
        this.registerForm.controls['assessTimepre'].clearValidators();
        this.registerForm.controls['assessTimepre'].updateValueAndValidity();
      }else if(e.target.value == 2){
        this.registerForm.controls['assessnamepost'].clearValidators();
        this.registerForm.controls['assessnamepost'].updateValueAndValidity();
        this.registerForm.controls['assessquescountpost'].clearValidators();
        this.registerForm.controls['assessquescountpost'].updateValueAndValidity();
        this.registerForm.controls['assessTimepost'].clearValidators();
        this.registerForm.controls['assessTimepost'].updateValueAndValidity();
      }
    }
  }

  onSubmit(value){
    this.submitted = true;
    if (this.registerForm.valid) {
    var senddata = {};
    let assessments = [{
      "name" : value.assessnamepre,
      "ques_count" : value.assessquescountpre,
      "duration" : value.assessTimepre,
      "assessment" : "pre"
    },
    {
      "name" : value.assessnamepost,
      "ques_count" : value.assessquescountpost,
      "duration" : value.assessnamepost,
      "assessment" : "post"
    }]
    let start_date = moment(value.startdate,'YYYY-MM-DD').format("YYYY-MM-DD");
    let to_date = moment(value.enddate,'YYYY-MM-DD').format("YYYY-MM-DD");
    var am=[];
    am.push(value.venue_am)
    if(value.is_feedback == true){
      value.is_feedback = 1
    }else{
      value.is_feedback = 0
    }
    senddata = {
      "title" : value.title,
      "description" : value.description,
      "startdate" : start_date,
      "enddate" : to_date,
      "starttime" : value.startTime+':00',
      "endtime" : value.endTime+':00',
      "is_feedback":value.is_feedback,
      "venue_type": value.venue_type,
      "venue_dealer": value.venue_dealer ,
      "venue_address" : value.venue_address,
      "assessments" : JSON.stringify(assessments),
      "dse" : JSON.stringify(this.typedsedata),
      "venue_am" : JSON.stringify(am)
    }
    this.loader = true;
      this.server.post("crtraining",senddata
      ).then((data) => {
        this.loader = false;
        if (data.status == 200 && data.result.response == "success") {
          let msg2 = "Training scheduled 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('');
        }
      })
   }else{
   }
  }

}
