import { Component, OnInit, ViewChild } from '@angular/core';
import { LocalStorage } from '../../core/services/local_storage.service';
import { HyperService } from '../../core/services/http.service';
import { Router, ActivatedRoute } from '@angular/router';
import * as moment from 'moment';
import { AddparticipantpopComponent } from '../addparticipantpop/addparticipantpop.component';
import { ConfirmpopComponent } from '../confirmpop/confirmpop.component';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { ToasterService } from '@service/toaster.service';

import {Subject, Observable} from 'rxjs';
import {WebcamImage, WebcamInitError, WebcamUtil} from 'ngx-webcam';

declare var $:any;

@Component({
  selector: 'app-trainingcourse',
  templateUrl: './trainingcourse.component.html',
  styleUrls: ['./trainingcourse.component.scss']
})
export class TrainingcourseComponent implements OnInit {
  sub: any;
  sch_id: any;
  training_detail: any = [];
  participant_data: any = [];
  is_addparticipant: boolean = false;
  addparticipantsmpin:any;
  loader: boolean;
  type: any;
  user_id: any;
  userData: any = {};
  zmmail:string='';
  rmmail:string='';
  ammail:string='';
  @ViewChild(AddparticipantpopComponent) participant_pop: AddparticipantpopComponent;
  @ViewChild(ConfirmpopComponent) confirm_pop: ConfirmpopComponent;
  schedule_data: any;
  showmodify: boolean;
  participant_list: any;
  dsedata: any;
  add_buttons: any=[];
  active_btn: any;
  isDisabled: boolean= true;
  attendance_code;
  reason_absent;
  manual_reason:any = {};
  scoreslist = {};
  comments = {};
  attendanceuserlist :any= [];
  checkclickdata: any;
  showeditattendance: boolean;
  tab_clicked: any = 1;
  scoreuserlist: any=[];
  schedule_attendance_data: any=[];
  remarks;
  newarray: any = [];
  editedscore: boolean;
  enter1st: boolean = true;
  dsedataattendance: any;
  showerror: boolean = false;
  showpresenterror: boolean = false;
  error_msg: any;
  is_imageselect: boolean = false;
  fileUrl: any;
  user_pro: any;
  datebetween: any=[];
  overallschedule_data: any;
  pic_click_from: any;
  group_profile: any;
  add_date_buttons=[];
  showfield: any;
  attendance_status: any;
  userimagelist : any = [];
  singleuser_profile: any;
  role_num: any;
  weightage_data: any;
  score_col: any = [];
  showcertified: boolean = false;
  showpre: boolean = false;
  showpost: boolean = false;
  showrole: boolean = false;
  showassign: boolean = false;
  showperform: boolean = false;
  overall_score:any = 0;
  certifiedpercentage: any;
  name_Of_certification: string = "Certification";
  rolepercentage: any;
  assignpercentage: any;
  performpercentage: any;
  roleerror: boolean = false;
  assignerror: boolean = false;
  performerror: boolean = false;
  temparray = [];
  summary_details: any;
  remarkerror: any;
  summary_attendance: any;
  scoresubmitdisable: boolean = false;
  reason_list: any;
  showtext: boolean;
  reason: any;
  other_reason: any;
  showtemperror: boolean;
  amreason_list: any = [];
  showamfield: any;
  am_acknow: any;
  notfiled: boolean = false;
  feedback_list: any;
  attendances_list: any = [];
  clickedcheck: boolean;
  showabsentees: boolean = false;
  showabsentees_trainer: boolean = false;
  trainingcurrent_day: any;
  constructor(private server: HyperService, private router: Router, private route: ActivatedRoute,public toaster : ToasterService) {
    this.sub = this.route.params.subscribe(params => {
      this.sch_id = (params['id']);
    });
  }

  ngOnInit() {
    this.role_num = LocalStorage.getValue('user_data').role;
    if(this.role_num == 10){
      this.router.navigateByUrl('trainer')
    }
    LocalStorage.setValue('is_firsttime', false);
    this.getdetails();
    this.getreasondata();
    this.getfeedback();
    // this.getdaywiserecord();
    WebcamUtil.getAvailableVideoInputs()
    .then((mediaDevices: MediaDeviceInfo[]) => {
      this.multipleWebcamsAvailable = mediaDevices && mediaDevices.length > 1;
    });
  }

  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('');
      }
    })
  }

  // https://hyper-m.cygnusa.in/_api/web/en_us/crtraining/trainingsfeedbacklist

  getfeedback(){
    this.server.get("crtraining/trainingsfeedbacklist").then((data) => {
      if (data.status == 200 && data.result.response == "success") {
        this.feedback_list= data.result.data;
        LocalStorage.setValue('DSEFeedbackdata',JSON.stringify(this.feedback_list))
      }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;
  }

  getdetails(){
    this.loader = true; 
    this.temparray = [];
    this.tab_clicked = 1;
    this.server.get("crtraining/"+this.sch_id).then((data) => {
      if (data.status == 200 && data.result.response == "success") {
        this.overallschedule_data= data.result.data[0];
        let temp_array = this.overallschedule_data.participant;
        temp_array.forEach((dse)=>{
          if(dse.status == 1 || dse.status == 0){
            this.temparray.push(dse)
          }
        })
        this.attendances_list = [];
        let userarray = [];
        temp_array.forEach((list)=>{
          if(list.attendance.length != 0){
            // userarray.push(list)
            if(list.attendance[0].ispresent != 2){
              userarray.push(list)
            }
          }
        });
        userarray.forEach((dse)=>{
          let count = 0;
          var attend = dse.attendance;
          attend.map((present)=>{
            if(present.ispresent == 1){
              count ++;
              if(count == attend.length){
                this.attendances_list.push(dse)
              }
            }
          })
          
        })

        if(this.overallschedule_data.current_day !=undefined && this.overallschedule_data.current_day !='' && this.overallschedule_data.current_day!=null){
          this.active_btn = this.overallschedule_data.current_day-1;
          this.showeditattendance = true;
        }else{
          this.active_btn = 0;
          this.showeditattendance = false;
        }
        this.trainingcurrent_day = this.overallschedule_data.current_day;
        this.getdaywiserecord();
        this.getweightagescore();
        this.getsummary();
        this.checkabsentees();
      } else if (data.result.response == "failed" && data.status == 401) {
        this.router.navigateByUrl('');
      }
    })
  }

  getdaywiserecord(){
    let currentdayindex=this.active_btn+1;
    var dateString = this.overallschedule_data.startdate;
    var date = new Date(dateString);
    var daysPrior = this.active_btn;
    date.setDate(date.getDate() + daysPrior);
    this.loader = true;  
    this.server.get("crtraining/"+this.sch_id+'/'+moment(date).format("YYYY-MM-DD")).then((data) => {
      this.loader = false;
      if (data.status == 200 && data.result.response == "success") {
        this.schedule_data = data.result.data[0];
        this.participant_list = this.schedule_data.participant;
        this.attendance_status = this.schedule_data.attendance_update_status;
        this.am_acknow = this.schedule_data.am_acknowledgement;
        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_buttons = [];
        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
            });
          }
        }
        this.setdays();
        setTimeout(() => {
          this.checkscore_submit();
          this.checkattendace_submit();
        }, 1000);
        // setTimeout(() => {
        //   let userarray = [];
        //   this.attendances_list.forEach((user)=>{
        //     var attend = user.attendance;
        //     attend.map((data)=>{
        //       if(data.ispresent == 2){
        //       $('.role'+user.userid).addClass("pre_post");
        //       $('.role'+user.userid).prop("readonly",true);
        //       $('.assign'+user.userid).addClass("pre_post");
        //       $('.assign'+user.userid).prop("readonly",true);
        //       $('.perform'+user.userid).addClass("pre_post");
        //       $('.perform'+user.userid).prop("readonly",true);
        //       $('.remark'+user.userid).css("background","#f6f6f6","!important");
        //       $('.remark'+user.userid).prop("readonly",true);
        //       $('.overall'+user.userid).addClass("pre_post");
        //       $('.certification'+user.userid).addClass('failure');
        //       $('.certification'+user.userid).text('Failed');
        //       $('.certification'+user.userid).attr('data-value',2);
        //       }
        //     })
        //   })
        // }, 1000);
      } else if (data.result.response == "failed" && data.status == 401) {
        this.router.navigateByUrl('');
      }
    })
  }
  
  getsummary(){
    this.server.get("crtraining/trainingsummery/"+this.sch_id).then((data) => {
      if (data.status == 200 && data.result.response == "success") {
        this.summary_details = data.result.data;
        this.summary_attendance = this.summary_details.attendance;
      } else if (data.result.response == "failed" && data.status == 401) {
        this.router.navigateByUrl('');
      }
    })
  }

  getweightagescore(){
    this.server.get("crtraining/traininglevelscore/"+this.overallschedule_data.lvl_id).then((data) => {
      if (data.status == 200 && data.result.response == "success") {
        this.weightage_data = data.result.data;
        this.weightage_data.forEach((item)=>{
          if(!this.showcertified){
            this.showcertified = item.id == 1 ? true : false;
            this.certifiedpercentage = item.percentage;
          }
          if(!this.showpre){
            this.showpre = item.id == 2 ? true : false;
          }
          if(!this.showpost){
            this.showpost = item.id == 3 ? true : false;
          }
          if(!this.showrole){
            this.showrole = item.id == 4 ? true : false;
            this.rolepercentage = item.percentage;
          }
          if(!this.showassign){
            this.showassign = item.id == 5 ? true : false;
            this.assignpercentage = item.percentage;
          }
          if(!this.showperform){
            this.showperform = item.id == 6 ? true : false;
            this.performpercentage = item.percentage;
          }
        });
        // var tab = $('#score_table tr th').length;
        // alert(tab);
      } else if (data.result.response == "failed" && data.status == 401) {
        this.router.navigateByUrl('');
      }
    })
  }

  viewimage(data){
    $('#previewModal').modal('show');
    this.singleuser_profile = data;
  }

  closecam(){
    this.showWebcam = !this.showWebcam;
  }

  setdays(){
    this.add_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'));
      currentDate.setDate(currentDate.getDate() + 1);
    }
    if(between.length == this.schedule_data.training_days){
      for (let i = 0; i <  this.schedule_data.training_days; i++) {
        this.add_buttons.push('Day'+' '+(i+1)+' '+'('+between[i]+')')
      }
    }else{
      for (let i = 0; i <  this.schedule_data.training_days; i++) {
        this.add_buttons.push('Day'+' '+ (i+1));
      }
    }
    setTimeout(()=>{
      this.setdisable();
    },1000)
  }

  setdisable(){
    for(let i=0;i<this.add_buttons.length;i++){
      if(!this.schedule_data.training_completed){
        if( i > this.active_btn && i > this.schedule_data.current_day - 1){
          $(".index_btn"+[i]).prop("disabled", true);
          $(".index_btn"+[i]).css("cursor", "no-drop");
        }else{
  
        }
      }
    }
     
    if(this.showeditattendance){
      for(let i=0;i<this.participant_list.length;i++){
        $(".text"+this.participant_list[i].userid).css("cursor", "no-drop");
        $(".text"+this.participant_list[i].userid).css("opacity", "0.75");
      }
    }
  }

  clickdate(index){
    this.active_btn = index;
    this.getdaywiserecord()
    this.showeditattendance = index == this.schedule_data.current_day - 1 ? true : false;
    setTimeout(()=>{
      if(this.showeditattendance){
        for(let i=0;i<this.participant_list.length;i++){
          $(".text"+this.participant_list[i].userid).prop("disabled", true);
          $(".text"+this.participant_list[i].userid).css("cursor", "no-drop");
          $(".text"+this.participant_list[i].userid).css("opacity", "0.75");
        }
      }else{
      }
    },500)
    setTimeout(()=>{
      this.setdisable();
    },1000)
    // setTimeout(()=>{
    //   if(this.attendanceuserlist.length!=0){
    //     for(let i=0;i<this.attendanceuserlist.length;i++){
    //       if(this.attendanceuserlist[i].ispresent == 1){
    //         $(".present"+this.attendanceuserlist[i].userid).css("cursor", "no-drop");
    //         $(".present"+this.attendanceuserlist[i].userid).css("pointer-events", "none");
    //         $(".present"+this.attendanceuserlist[i].userid).css("background", "#00b050");
    //         $(".absent"+this.attendanceuserlist[i].userid).css("cursor", "no-drop");
    //         $(".absent"+this.attendanceuserlist[i].userid).prop("disabled", true);
    //         $(".check"+this.attendanceuserlist[i].userid).prop("disabled", true);
    //         $(".check"+this.attendanceuserlist[i].userid).css("cursor", "no-drop");
    //       }else if(this.attendanceuserlist[i].ispresent == 2){
    //         $(".present"+this.attendanceuserlist[i].userid).prop("disabled", true);
    //         $(".absent"+this.attendanceuserlist[i].userid).css("pointer-events", "none");
    //         $(".absent"+this.attendanceuserlist[i].userid).css("background", "#ff0000");
    //         $(".present"+this.attendanceuserlist[i].userid).css("cursor", "no-drop");
    //         $(".absent"+this.attendanceuserlist[i].userid).css("cursor", "no-drop");
    //         $(".check"+this.attendanceuserlist[i].userid).prop("disabled", true);
    //         $(".check"+this.attendanceuserlist[i].userid).css("cursor", "no-drop");
    //       }else if(this.attendanceuserlist[i].ispresent == 0){
  
    //       }
    //     }
    //   }
    // },1000)
    
  }

  tabclick(tabid){
    $('.submitatt').css("display","none");
    $('.remark_emptyerr').css('display','none');
    this.tab_clicked = tabid;
  }

  clickprofile(index,data){
    this.showWebcam = true;
    this.pic_click_from = index;
    if(index == 2){
      this.user_pro = data;
      $('#webcammodal').modal('show');
      $('#webcammodal').find('.modal-body').attr('data-value',this.user_pro.userid);
      $('#webcammodal').find('.cambtn').attr('data-value',this.user_pro.userid);
    }else{
      $('#webcammodal').modal('show');
    }
    
  }

  attendance_present(dse){
    let photo = dse.attendance != null && dse.attendance != '' && dse.attendance != undefined ? dse.attendance.image : '';
    this.server.post("crtraining/trainingattendancenotificationupdate",
    {'schedule_id' : this.sch_id,'userid':dse.userid,'otp':this.attendance_code}).then((data) => {
    this.loader = false;
    if (data.status == 200 && data.result.response == "success") {
      this.showpresenterror = false;
      $(".present"+dse.userid).css("cursor", "no-drop");
      $(".present"+dse.userid).css("pointer-events", "none");
      $(".present"+dse.userid).css("background", "#00b050");
      $(".absent"+dse.userid).css("cursor", "no-drop");
      $(".absent"+dse.userid).prop("disabled", true);
      $(".check"+dse.userid).prop("disabled", true);
      $(".check"+dse.userid).css("cursor", "no-drop");
      $('.attenderr'+data.userid).css("display", "none");
      $('.load'+dse.userid).removeClass('disable_photo');

      this.notfiled = true;
      let senddata = {
        upload_photo : photo,
        // day : this.schedule_data.current_day,
        day : this.active_btn+1,
        ispresent : 1,
        userid : dse.userid,
        manual_attendance_reason : '',
        absence_reason : ''
      }
      
      if(this.attendanceuserlist.length!=0){
        let objIndex = this.attendanceuserlist.findIndex((obj => obj.userid == dse.userid));
        if(objIndex == -1){
          this.attendanceuserlist.push(senddata)
        }else{
          this.attendanceuserlist[objIndex].day = senddata.day;
          this.attendanceuserlist[objIndex].ispresent = senddata.ispresent;  
          this.attendanceuserlist[objIndex].manual_attendance_reason = senddata.manual_attendance_reason;  
          this.attendanceuserlist[objIndex].absence_reason = senddata.absence_reason;  
        }
      }else{
        this.attendanceuserlist.push(senddata);
      }
      this.attendance_code = '';
      this.error_msg = '';
      $('#sendcodemodal').modal('hide');
      } else if (data.result.response == "failed") {
        this.showpresenterror = true;
        this.error_msg = data.result.message;
      }
    })
  }

  attendance_absent(dse){
    let photo = dse.attendance != null && dse.attendance != '' && dse.attendance != undefined ? dse.attendance.image : '';
    if(this.reason_absent !=null && this.reason_absent !=undefined && this.reason_absent !=''){
      this.showerror = false;
      $(".present"+dse.userid).prop("disabled", true);
      $(".absent"+dse.userid).css("background", "#ff0000");
      // $(".absent"+dse.userid).css("pointer-events", "none");
      $(".present"+dse.userid).css("cursor", "no-drop");
      // $(".absent"+dse.userid).css("cursor", "no-drop");
      $(".check"+dse.userid).prop("disabled", true);
      $(".check"+dse.userid).css("cursor", "no-drop");
      $('.attenderr'+dse.userid).css("display", "none");
      $('.load'+dse.userid).addClass('disable_photo');
      this.notfiled = true;
      let senddata = {
        upload_photo : photo,
        // day : this.schedule_data.current_day,
        day : this.active_btn+1,
        ispresent : 2,
        userid : dse.userid,
        manual_attendance_reason : '',
        absence_reason : this.reason_absent
      }

      if(this.attendanceuserlist.length!=0){
        let objIndex = this.attendanceuserlist.findIndex((obj => obj.userid == dse.userid));
        if(objIndex == -1){
          this.attendanceuserlist.push(senddata)
        }else{
          this.attendanceuserlist[objIndex].day = senddata.day;
          this.attendanceuserlist[objIndex].ispresent = senddata.ispresent;  
          this.attendanceuserlist[objIndex].manual_attendance_reason = senddata.manual_attendance_reason;  
          this.attendanceuserlist[objIndex].absence_reason = senddata.absence_reason;  
        }
      }else{
        this.attendanceuserlist.push(senddata);
      }
      this.reason_absent = '';
      $('#reasonmodal').modal('hide');
    }else{
      this.showerror = true;
      // this.toaster.show('Please give reason for Absent');
    }
  }

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

  onCancel(){
    if(this.type!="mobile"){
      this.router.navigateByUrl('trainer');
    }else{
      this.router.navigateByUrl('trainer/' +this.type+'/'+this.userData.emailid+'/'+this.user_id);
    }
  }

  cancelmodal(){
    this.attendance_code = '';
    this.reason_absent = '';
  }
  
  reasonsend(data,val){
    $('#reasonmodal').modal('show');
    this.dsedata = data;
    this.showfield = val;
    if(this.attendanceuserlist.length !=0){
      this.attendanceuserlist.forEach((list)=>{
        if(list.ispresent == 2 && list.userid == this.dsedata.userid){
          this.reason_absent = list.absence_reason;
        }
      })
    }
  }

  amreasonsend(data,val){
    $('#amreasonmodal').modal('show');
    this.dsedata = data;
    this.showamfield = val;
    if(this.amreason_list.length !=0){
      this.amreason_list.forEach((list)=>{
        if(list.userid == this.dsedata.userid){
          this.reason = list.am_absence_reason;
          if(this.reason == 6){
            this.other_reason = list.am_absence_reason_desc;
            this.showtext = true;
          }
        }
      })
    }
  }

  cancelammodal(){
    $('#amreasonmodal').modal('hide');
    this.showerror = false;
    this.showtemperror = false;
    this.reason = '';
    this.other_reason = '';
  }

  saveam_reason(data){
    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;
          this.saveam_data(data)
        }else{
          this.showtemperror = true;
        }
      }else{  
        this.showerror = false;
        this.showtext = false;
        this.saveam_data(data)
      }
    }else{
      this.showerror = true;
    }
  }

  saveam_data(res){
    // $(".absent"+res.userid).css("pointer-events", "none");
    let senddata = {
      userid : res.userid,
      am_absence_reason : this.reason,
      am_absence_reason_desc : this.other_reason
    }
    
    if(this.amreason_list.length!=0){
      let objIndex = this.amreason_list.findIndex((obj => obj.userid == res.userid));
      if(objIndex == -1){
        this.amreason_list.push(senddata)
      }else{
        this.amreason_list[objIndex].userid = senddata.userid;
        this.amreason_list[objIndex].am_absence_reason = senddata.am_absence_reason;  
        this.amreason_list[objIndex].am_absence_reason_desc = senddata.am_absence_reason_desc;  
      }
    }else{
      this.amreason_list.push(senddata);
    }
    this.reason = '';
    this.other_reason = '';
    $('#amreasonmodal').modal('hide');
  }

  codesend(data){
    this.error_msg = '';
    $('#sendcodemodal').modal('show');
    this.dsedata = data;
    this.server.post("crtraining/trainingattendancenotification",
      {'schedule_id' : this.sch_id,
      'userid' : data.userid}).then((data) => {
      this.loader = false;
      if (data.status == 200 && data.result.response == "success") {
       
      } else if (data.result.response == "failed") {
      }
    })
  }

  clickCheckbox(data,index){
    var data_id = data.userid;
    this.checkclickdata = data;
    if ($(".check"+data_id+":checked").length > 0) {
      this.clickedcheck = true;
      $(".text"+data_id).prop("disabled", false);
      $(".text"+data_id).css("opacity", "1");
      $(".text"+data_id).css("cursor", "auto");
      $(".present"+data_id).prop("disabled", true);
      $(".absent"+data_id).prop("disabled", true);
      $(".present"+data_id).css("cursor", "no-drop");
      $(".absent"+data_id).css("cursor", "no-drop");
    } else {
      $('.submitatt_manual').css('display','none');
      this.clickedcheck = false;
      $(".text"+data_id).prop("disabled", true);
      $(".text"+data_id).css("opacity", "0.75");
      $(".text"+data_id).css("cursor", "no-drop");
      $(".present"+data_id).prop("disabled", false);
      $(".absent"+data_id).prop("disabled", false);
      $(".present"+data_id).css("cursor", "pointer");
      $(".absent"+data_id).css("cursor", "pointer");
      this.manual_reason[data_id] = '';
      }
  }

  dataChanged(e){
  }

  isValidate(role,assign,perform,comment,from,data){
    if(from == 'role'){
      this.roleerror = Number(role) <= Number(this.rolepercentage) ? false : true;
      this.roleerror ? $('.roleerr'+data.userid).css("display", "block") : $('.roleerr'+data.userid).css("display", "none");
    }
    if(from == 'assign'){
      this.assignerror = Number(assign) <= Number(this.assignpercentage) ? false : true;
      this.assignerror ? $('.assignerr'+data.userid).css("display", "block") : $('.assignerr'+data.userid).css("display", "none");
    }
    if(from == 'perform'){
      this.performerror = Number(perform) <= Number(this.performpercentage) ? false : true;
      this.performerror ? $('.performerr'+data.userid).css("display", "block") : $('.performerr'+data.userid).css("display", "none");
    }
    if(from == 'remark'){
      this.remarkerror =  60 <= comment.length ? false : true;
      this.remarkerror ? $('.remarkerror'+data.userid).css("display", "block") : $('.remarkerror'+data.userid).css("display", "none");
    }
    if(this.showrole && this.showassign && this.showperform){
      return (!this.roleerror && !this.assignerror && !this.performerror);
    }else if(this.showrole && this.showassign && !this.showperform){
      return (!this.roleerror && !this.assignerror);
    }else if(this.showrole && !this.showassign && !this.showperform){
      return (!this.roleerror);
    }else {
      return (!this.roleerror && !this.assignerror || !this.performerror);
    }
  }

  restrictAlphabets(e) {
    var x = e.which || e.keycode;
    if ((x >= 48 && x <= 57))
        return true;
    else
        return false;
  }

  onenterscroe(e,data,from){
    let pre = $('.pretest'+data.userid).val() ? $('.pretest'+data.userid).val() : 0;
    let post = $('.posttest'+data.userid).val() ? $('.posttest'+data.userid).val() : 0;
    let role = $('.role'+data.userid).val() ? $('.role'+data.userid).val() : 0;
    let assign = $('.assign'+data.userid).val() ? $('.assign'+data.userid).val() : 0;
    let perform = $('.perform'+data.userid).val() ? $('.perform'+data.userid).val() : 0;
    let comments = $('.remark'+data.userid).val() ? $('.remark'+data.userid).val() : '';
    if(this.isValidate(role,assign,perform,comments,from,data)){
      if( from != 'remark'){
        this.overall_score = Number(pre) + Number(post) + Number(role) + Number(assign) + Number(perform);
        $('.overall'+data.userid).val(this.overall_score);
        if(Number(this.overall_score) < Number(this.certifiedpercentage)){
          $('.certification'+data.userid).removeClass('success');
          $('.certification'+data.userid).addClass('failure');
          $('.certification'+data.userid).text('Failed');
          $('.certification'+data.userid).attr('data-value',2);
        }else{
          $('.certification'+data.userid).removeClass('failure');
          $('.certification'+data.userid).addClass('success');
          $('.certification'+data.userid).text('Certified');
          $('.certification'+data.userid).attr('data-value',1);
        }
      }
    
      let sendscoredata = {
        roleplay_or_demo : $('.role'+data.userid).val() ? $('.role'+data.userid).val() : '',
        assignment : $('.assign'+data.userid).val() ? $('.assign'+data.userid).val() : '',
        performance : $('.perform'+data.userid).val() ? $('.perform'+data.userid).val() : '',
        remarks : $('.remark'+data.userid).val() ? $('.remark'+data.userid).val() : '',
        certification : $('.certification'+data.userid).attr('data-value'),
        userid : data.userid,
        overall : $('.overall'+data.userid).val() ? $('.overall'+data.userid).val() : '' 
      }
      if(this.scoreuserlist.length!=0){
        let objIndex = this.scoreuserlist.findIndex((obj => obj.userid == data.userid));
        if(objIndex == -1){
          this.scoreuserlist.push(sendscoredata)
        }else{
          this.scoreuserlist[objIndex].roleplay_or_demo = sendscoredata.roleplay_or_demo;
          this.scoreuserlist[objIndex].assignment = sendscoredata.assignment;  
          this.scoreuserlist[objIndex].performance = sendscoredata.performance;  
          this.scoreuserlist[objIndex].certification = sendscoredata.certification;  
          this.scoreuserlist[objIndex].userid = sendscoredata.userid;  
          this.scoreuserlist[objIndex].overall = sendscoredata.overall;  
          this.scoreuserlist[objIndex].remarks = sendscoredata.remarks;  
        }
      }else{
        this.scoreuserlist.push(sendscoredata);
      }
    }
  }

  onentermanualreason(e,data){
    this.clickedcheck = false;
    let photo = data.attendance != null && data.attendance != '' && data.attendance != undefined ? data.attendance.image : '';

    let enteredreason = $('.text'+data.userid).val() ? $('.text'+data.userid).val() : 0;
    $('.load'+data.userid).removeClass('disable_photo');
    let senddata = {
      upload_photo : photo,
      day : this.active_btn+1,
      ispresent : 1,
      userid : data.userid,
      manual_attendance_reason : enteredreason,
      absence_reason : ''
    }
    if(this.attendanceuserlist.length!=0){
      let objIndex = this.attendanceuserlist.findIndex((obj => obj.userid == data.userid));
      if(objIndex == -1){
        this.attendanceuserlist.push(senddata)
      }else{
        this.attendanceuserlist[objIndex].day = senddata.day;
        this.attendanceuserlist[objIndex].ispresent = senddata.ispresent;  
        this.attendanceuserlist[objIndex].manual_attendance_reason = senddata.manual_attendance_reason;  
        this.attendanceuserlist[objIndex].absence_reason = senddata.absence_reason;  
      }
    }else{
      this.attendanceuserlist.push(senddata);
    }
  }

  upload($event,data) {
    let files = $event.target.files[0]
    let size_check=files.size;
    const file = Math.round((size_check / 1024));
    var ext = files.name.substring(files.name.lastIndexOf('.') + 1);
    if (ext.toLowerCase() == 'png' || ext.toLowerCase() == 'jpg' || ext.toLowerCase() == 'jpeg') {
      this.is_imageselect = true;
      var reader = new FileReader();
      reader.readAsDataURL(files); 
      reader.onload = (event) => { 
        this.fileUrl = ( < FileReader > event.target).result;
        // $('upload_img'+data.userid).attr('src', this.fileUrl);
        // $("#img-remove").show();
      }
    } else if (ext.toLowerCase() != 'png' || ext.toLowerCase() != 'jpg' || ext.toLowerCase() != 'jpeg') {
      this.is_imageselect = false;
    } else {
      this.is_imageselect = false;
    }
  }

  onSaveattendance(){
    let count = 0;
    let presentlength = [];
    if(this.attendanceuserlist.length!=0){
      if(this.clickedcheck){
        $('.submitatt_manual').css('display','block');
      }else{
        $('.submitatt_manual').css('display','none');
        this.attendanceuserlist.forEach((list)=>{
          if(list.ispresent == 1){
            presentlength.push(list)
            if(list.upload_photo == '' || list.upload_photo == null || list.upload_photo == undefined){
              $('.userpic'+list.userid).css('display','block');
              $('.imageerr').css('display','block');
            }else{
              $('.userpic'+list.userid).css('display','none');
              count ++;
            }
          }
        })
        if(count == presentlength.length){
          // alert('success')
          $('.imageerr').css('display','none');
          this.submitattendance('1');
        }
      }
    }
    // let keys = Object.keys(this.manual_reason);
    //   let senddata;
    //   if(keys.length != 0){
    //     for(let i=0;i<keys.length;i++){
    //       if(this.manual_reason[keys[i]] !='' && this.manual_reason[keys[i]]!=undefined && this.manual_reason[keys[i]]!=null){
    //         senddata = {
    //           // upload_photo : '',
    //           day : this.active_btn+1,
    //           ispresent : 0,
    //           userid : keys[i],
    //           manual_attendance_reason : this.manual_reason[keys[i]],
    //           absence_reason : ''
    //         }
    //         this.attendanceuserlist.push(senddata);
    //       }
    //     }
    //     setTimeout(() => {
    //       this.submitattendance('1');
    //     }, 1000);
    //   }else{
    //     if(this.attendanceuserlist.length!=0){
    //       this.submitattendance('1');
    //     }else{
    //       this.toaster.show('Please give attendance')
    //     }
    //   }
  }

  onSavescore(){
    let count = 0;
    if(this.scoreuserlist.length!=0){
      this.scoreuserlist.forEach((list)=>{
        if(list.remarks == '' || list.remarks == null || list.remarks == undefined){
          $('.remarkreqerror'+list.userid).css('display','block');
          $('.remark_emptyerr').css('display','block');
        }else{
          $('.remarkreqerror'+list.userid).css('display','none');
          count ++;
        }
      })
      if(count == this.scoreuserlist.length){
        // alert('success')
        $('.remark_emptyerr').css('display','none');
        this.submitscore('1');
      }
    }


    // let score_keys = Object.keys(this.scoreslist);
    // let comments_keys = Object.keys(this.comments);
    // let sendscoredata = {};

      // if(score_keys.length != 0){
      //   if(comments_keys.length!=0){
      //     this.loader = true;
      //     for(let i=0;i<score_keys.length;i++){
      //     if((this.scoreslist[score_keys[i]] !='' && this.scoreslist[score_keys[i]]!=undefined && this.scoreslist[score_keys[i]]!=null)){
      //       if(this.comments[comments_keys[i]] !='' && this.comments[comments_keys[i]]!=undefined && this.comments[comments_keys[i]]!=null){
      //         sendscoredata = {
      //           score : this.scoreslist[score_keys[i]],
      //           remarks : this.comments[comments_keys[i]],
      //           userid : score_keys[i]
      //         }
      //         let objIndex = this.scoreuserlist.findIndex((obj => obj.userid == score_keys[i]));
      //         if(objIndex == -1){
      //           this.scoreuserlist.push(sendscoredata)
      //         }else{
      //           this.scoreuserlist[objIndex].score = this.scoreslist[score_keys[i]];
      //           this.scoreuserlist[objIndex].remarks = this.comments[comments_keys[i]];  
      //         }
      //         // this.scoreuserlist.push(sendscoredata);
      //       }else{
      //         this.toaster.show('Please give Comments');
      //         return false;
      //       }
      //     }else{
      //       this.toaster.show('Please give Score & Comments');
      //       return false;
      //     }
      //   }
      //   setTimeout(() => {
      //     this.submitscore();
      //   },1000);
      //   }else{
      //     this.toaster.show('Please give Comments..');
      //   }
      // }else{
      //   if(this.scoreuserlist.length!=0){
      //     this.submitscore();
      //   }else{
      //     this.toaster.show('Please give score & Comments')
      //   }
      // }
  }

  submitattendance(val){
    this.manual_reason = {};
    let senddata = {};
    if(val == 1){
      senddata = {'schedule_id' : this.sch_id,
      'attendance' : JSON.stringify(this.attendanceuserlist),'attendance_submit' : 0}
    }else{
      senddata = {'schedule_id' : this.sch_id,
      'attendance' : JSON.stringify(this.attendanceuserlist),'attendance_submit' : 1 }
    }
    this.loader = true;
    this.server.post("crtraining/updatetrainingpresentabsent",senddata).then((data) => {
      this.loader = false;
      if (data.status == 200 && data.result.response == "success") {
        this.attendanceuserlist = [];
        let msg2 = "Training Attendance Saved Successfully";
        this.confirm_pop.confirmPopups(msg2, (data) => {
          this.getdetails();
        this.router.navigateByUrl('trainingcourse/'+this.sch_id);
      })
      } else if (data.result.response == "failed" && data.status == 401) {
        this.router.navigateByUrl('');
      }
    })
  }

  submitscore(val){
    this.scoreslist = {};
    this.comments = {};
    let senddata = {};
    if(val == '1'){
      senddata = {'schedule_id' : this.sch_id,
      'score' : JSON.stringify(this.scoreuserlist),'score_submit' : 0}
    }else if(val == '2'){
      senddata = {'schedule_id' : this.sch_id,
    'score' : JSON.stringify(this.scoreuserlist),'score_submit' : 1 }
    }else{
      senddata = {'schedule_id' : this.sch_id,
      'score' : JSON.stringify(this.scoreuserlist),'score_submit' : 2 }
    }
    this.loader = true;
    this.server.post("crtraining/updatetrainingscore",senddata).then((data) => {
      this.loader = false;
      if (data.status == 200 && data.result.response == "success") {
        this.scoreuserlist = [];
        let msg2 ;
        if(val == 1){
          msg2 = "Training Score Saved Successfully"
        }else if(val == 2){
          msg2 = "Training Score Submitted Successfully"
        }else{
          msg2 = "Training Finished Successfully"
        }
        
        // let msg2 = val == 3 ? "Training Finished successfully" : "Training Score Submitted successfully";
        this.confirm_pop.confirmPopups(msg2, (data) => {
          this.getdetails();
        this.router.navigateByUrl('trainingcourse/'+this.sch_id);
      })
      } else if (data.result.response == "failed" && data.status == 401) {
        this.router.navigateByUrl('');
      }
    })
  }

  onSubmitattendance(){
    // let firstarray = [];
    // let secarray = [];
    // let count = 0;
    // this.temparray.forEach((data)=>{
    //   data.attendance.forEach((day)=>{
    //     firstarray.push({
    //       'day' : day.day ,
    //       'userid' : data.userid,
    //       'ispresent' : day.ispresent,
    //       'manual_attendance_reason' : day.manual_attendance_reason,
    //       'absence_reason' : day.absence_reason
    //     })
    //   });

    //   let userid = data.userid;
    //   let attendant_data;
    //   if(data.attendance.length != this.schedule_data.training_days){
    //     attendant_data = data.attendance;
    //     let day = Number(this.active_btn) + 1;
    //     firstarray.forEach((item)=>{
    //       if(item.day == day){
    //         data.userid ?  $('.attenderr'+data.userid).css("display", "block") :  $('.attenderr'+data.userid).css("display", "none")
    //         if(day == this.schedule_data.training_days){
    //           $('.submitatt').css("display","none");
    //           $('.submitcheck').css("display","block");
    //         }else{
    //           $('.submitcheck').css("display","none");
    //           $('.submitatt').css("display","block");
    //         }
    //       }
    //      });
    //   }else{
    //     count++;
    //   }
    // });
    // let attendancesubmit_array = [];
    // let currenday = this.overallschedule_data.current_day;
    // // this.add_buttons.forEach((btn)=>{

    // // })
    // for (let i = 0; i <  currenday; i++) {
    //   attendancesubmit_array.push(1)
    // }
    //  if(count == this.temparray.length){
    //   let senddata = {'schedule_id' : this.sch_id,
    //   'attendance' : JSON.stringify(firstarray),'attendance_submit' : 1}
    //   this.loader = true;
    //   this.server.post("crtraining/updatetrainingpresentabsent",senddata).then((data) => {
    //   this.loader = false;
    //     if (data.status == 200 && data.result.response == "success") {
    //       this.scoreuserlist = [];
    //       let msg2 = "Training Attendance Submitted Successfully";
    //       this.confirm_pop.confirmPopups(msg2, (data) => {
    //         this.getdetails();
    //       this.router.navigateByUrl('trainingcourse/'+this.sch_id);
    //     })
    //     } else if (data.result.response == "failed") {
    //     }
    //   })
    // } 
    let firstarray = [];
    let secarray = [];
    let checkday = Number(this.active_btn)+Number(1);
    this.temparray.forEach((data)=>{
      data.attendance.forEach((day)=>{
        if(checkday == day.day){
          firstarray.push({
            'day' : day.day ,
            'userid' : data.userid,
            'ispresent' : day.ispresent,
            'manual_attendance_reason' : day.manual_attendance_reason,
            'absence_reason' : day.absence_reason
          })
        }
      });
    });
    this.participant_list.forEach((list)=>{
      if(list.status == 1 || list.status == 0){
        secarray.push(list);
      }
    });
    if(firstarray.length == secarray.length){
      $('.submitatt').css("display","none");
      let submisson_code = [];
      for(let j = 0 ;j<checkday ;j++){
        submisson_code.push(1)
      }    
      let senddata = {'schedule_id' : this.sch_id,
      'attendance' : JSON.stringify(firstarray),'attendance_submit' : JSON.stringify(submisson_code)}
      this.loader = true;
      this.server.post("crtraining/updatetrainingpresentabsent",senddata).then((data) => {
      this.loader = false;
        if (data.status == 200 && data.result.response == "success") {
          this.scoreuserlist = [];
          let msg2 = "Training Attendance Submitted Successfully";
          this.confirm_pop.confirmPopups(msg2, (data) => {
            this.getdetails();
            this.router.navigateByUrl('trainingcourse/'+this.sch_id);
          })
        } else if (data.result.response == "failed" && data.status == 401) {
          this.router.navigateByUrl('');
        }
      })
    }else{
      $('.submitatt').css("display","block");
    }
    
  }

  checkattendace_submit(){
    let firstarray = [];
    let count = 0;
    let checkday = Number(this.active_btn)+Number(1);
    this.temparray.forEach((data)=>{
      data.attendance.forEach((day)=>{
        if(checkday  == day.day)
        firstarray.push({
          'day' : day.day ,
          'userid' : data.userid,
          'ispresent' : day.ispresent,
          'manual_attendance_reason' : day.manual_attendance_reason,
          'absence_reason' : day.absence_reason
        })
      });
      if(firstarray.length != this.temparray.length){
        this.notfiled = true;
      }else{
        this.notfiled = false;
      }
    });
  }

  checkabsentees(){
    let firstarray = [];
    this.temparray.forEach((data)=>{
      data.attendance.forEach((day)=>{
        if(day.ispresent == 2 && data.am_absence_reason!=''){
          this.showabsentees = true;
        }
        if(this.role_num != 5){
          if(day.ispresent == 2){
            this.showabsentees_trainer = true;
          }
        }
      });
    });
  }

  checkscore_submit(){
    let firstarray = [];
    this.attendances_list.forEach((data)=>{
      firstarray.push({
        'userid' : data.userid,
        'roleplay_or_demo' : data.roleplay_or_demo,
        'assignment' : data.assignment,
        'performance' : data.performance,
        'overall' : data.overall,
        'certification' : data.certification,
        'remarks' : data.remarks
      });
    });
    let roleErr = this.showrole ? true : false;
    let assignErr = this.showassign ? true : false;
    let performErr = this.showperform ? true : false;
    firstarray.forEach((item)=>{
      if(this.showrole){
        roleErr = item.roleplay_or_demo =='' ? true : false;
      }
      if(this.showassign){
        assignErr = item.assignment =='' ? true : false;
      }
      if(this.showperform){
        performErr = item.performance =='' ? true : false;
      }
    });
    if((roleErr || assignErr || performErr) == true){
      this.scoresubmitdisable = true;
    }
    else{
      this.scoresubmitdisable = false;
    }
  }

  onSubmitscore(val){ 
    let firstarray = [];
    this.attendances_list.forEach((data)=>{
      firstarray.push({
        'userid' : data.userid,
        'roleplay_or_demo' : data.roleplay_or_demo,
        'assignment' : data.assignment,
        'performance' : data.performance,
        'overall' : data.overall,
        'certification' : data.certification,
        'remarks' : data.remarks
      });
    });
    let roleErr = this.showrole ? true : false;
    let assignErr = this.showassign ? true : false;
    let performErr = this.showperform ? true : false;

    if(this.showrole){
      firstarray.forEach((item)=>{
        if(item.roleplay_or_demo ==''){
          $('.roleerr'+item.userid).css("display", "block");
          roleErr = true;
        }else{
          $('.roleerr'+item.userid).css("display", "none");
          roleErr = false;
        } 
      });
      this.scoreuserlist.forEach((item)=>{
        if(item.roleplay_or_demo ==''){
          $('.roleerr'+item.userid).css("display", "block")
          roleErr = true;
        }else{
          $('.roleerr'+item.userid).css("display", "none");
          roleErr = false;
        } 
      });
    }
    if(this.showassign){
      firstarray.forEach((item)=>{
        if(item.assignment ==''){
          $('.assignerr'+item.userid).css("display", "block")
          assignErr = true;
        }else{
          $('.assignerr'+item.userid).css("display", "none");
          assignErr = false;
        } 
      });
      this.scoreuserlist.forEach((item)=>{
        if(item.assignment ==''){
          $('.assignerr'+item.userid).css("display", "block");
          assignErr = true;
        }else{
          $('.assignerr'+item.userid).css("display", "none");
          assignErr = false;
        }
      });
    }
    if(this.showperform){
      firstarray.forEach((item)=>{
        if(item.performance ==''){
          $('.performerr'+item.userid).css("display", "block")
          performErr = true;
        }else{
          $('.performerr'+item.userid).css("display", "none");
          performErr = false;
        }
      });
      this.scoreuserlist.forEach((item)=>{
        if(item.performance ==''){
          $('.performerr'+item.userid).css("display", "block");
          performErr = true;
        }else{
          $('.performerr'+item.userid).css("display", "none");
          performErr = false;
        }
      })
    }
    if((roleErr || assignErr || performErr) == true){
    }else if(this.scoreuserlist.length!=0){
      if(val == '1'){
        this.submitscore('2');
      }else{
        this.submitscore('3');
      }
    }
    else{
      let senddata = {}
      if(val == '1'){
        senddata = {'schedule_id' : this.sch_id,
      'score' : JSON.stringify(firstarray),'score_submit' : 1 }
      }else {
        senddata = {'schedule_id' : this.sch_id,
      'score' : JSON.stringify(firstarray),'score_submit' : 2 }
      }
      this.loader = true;
      this.server.post("crtraining/updatetrainingscore",senddata).then((data) => {
        this.loader = false;
        if (data.status == 200 && data.result.response == "success") {
          this.scoreuserlist = [];
          let msg2 = val == 1 ? "Training Score Submitted Successfully" : "Training Finished Successfully";
          this.confirm_pop.confirmPopups(msg2, (data) => {
            this.getdetails();
          this.router.navigateByUrl('trainingcourse/'+this.sch_id);
        })
        } else if (data.result.response == "failed" && data.status == 401) {
          this.router.navigateByUrl('');
        }
      })
    }
  }

  
  onfinishtraining(){
    this.onSubmitscore('2')
  }

  send_grouppic(){
    const file = this.DataURIToBlob(this.group_profile,'group')
    this.server.fileUpload("crtraining/traininggroupimage", {
      'schedule_id' : this.sch_id,
      'file' : file
    }, true, (data) => {
    })
  }

  // unescape
  DataURIToBlob(dataURI: string, fileName : string):File {
    const splitDataURI = dataURI.split(',')
    const byteString = splitDataURI[0].indexOf('base64') >= 0 ? atob(splitDataURI[1]) : decodeURI(splitDataURI[1])
    const mimeString = splitDataURI[0].split(':')[1].split(';')[0];
    let exe = mimeString.split('/')[1];
    exe = exe != undefined && exe != '' && exe != null ? exe : 'png';
    let file_name = fileName+'.'+exe;
    const ia = new Uint8Array(byteString.length)
    for (let i = 0; i < byteString.length; i++)
        ia[i] = byteString.charCodeAt(i)

    return new File([ia], file_name,{ type: mimeString })
  }

  // Webcam
  public showWebcam;
  public allowCameraSwitch = true;
  public multipleWebcamsAvailable = false;
  public deviceId: string;
  public videoOptions: MediaTrackConstraints = {
    // width: {ideal: 1024},
    // height: {ideal: 576}
  };
  public errors: WebcamInitError[] = [];

  // latest snapshot
  public webcamImage: WebcamImage = null;

  // webcam snapshot trigger
  private trigger: Subject<void> = new Subject<void>();
  // switch to next / previous / specific webcam; true/false: forward/backwards, string: deviceId
  private nextWebcam: Subject<boolean|string> = new Subject<boolean|string>();



  public triggerSnapshot(): void {
    this.showWebcam = !this.showWebcam;
    this.trigger.next();
  }

  public toggleWebcam(): void {
    this.showWebcam = !this.showWebcam;
  }

  public handleInitError(error: WebcamInitError): void {
    this.errors.push(error);
  }

  public showNextWebcam(directionOrDeviceId: boolean|string): void {
    this.nextWebcam.next(directionOrDeviceId);
  }

  public handleImage(webcamImage: WebcamImage): void {
    this.webcamImage = webcamImage;
    if(this.pic_click_from == 2){
      $(".load"+this.user_pro.userid).css("display", "none");
      $(".image"+this.user_pro.userid).css("display", "block");
      $('.preview_img'+this.user_pro.userid).attr("src",this.webcamImage.imageAsDataUrl);
      $(".preview_img"+this.user_pro.userid).css("height", "70px");

      let senddata={
        upload_photo : this.webcamImage.imageAsDataUrl,
        userid : this.user_pro.userid,
      }
      if(this.attendanceuserlist.length!=0){
        let objIndex = this.attendanceuserlist.findIndex((obj => obj.userid == this.user_pro.userid));
        if(objIndex == -1){
          this.attendanceuserlist.push(senddata)
        }else{
          this.attendanceuserlist[objIndex].upload_photo = senddata.upload_photo;
        }
      }else{
        this.attendanceuserlist.push(senddata);
      }
    }else{
      $('.group-photo').css("display","none");
      $('.old_group').css("display","none");
      $('.group_img').attr("src",this.webcamImage.imageAsDataUrl);
      this.group_profile = this.webcamImage.imageAsDataUrl;
      this.send_grouppic();
    }
  }

  public cameraWasSwitched(deviceId: string): void {
    this.deviceId = deviceId;
  }

  public get triggerObservable(): Observable<void> {
    return this.trigger.asObservable();
  }

  public get nextWebcamObservable(): Observable<boolean|string> {
    return this.nextWebcam.asObservable();
  }
  // Webcamfunction
  onTakegroupphoto(){
    
  }

  onam_acknowlege(){
    let firstarray = [];
    let obj_data={};
    this.temparray.forEach((data)=>{
      data.attendance.forEach((day)=>{
        if(day.ispresent == 2){
          let objIndex = firstarray.findIndex((obj => obj.userid == data.userid));
          if(objIndex == -1){
            firstarray.push({
              'day' : day.day ,
              'userid' : data.userid,
              'ispresent' : day.ispresent,
              'manual_attendance_reason' : day.manual_attendance_reason,
              'absence_reason' : day.absence_reason
            })
          }else{
            firstarray[objIndex].day = day.day;
            firstarray[objIndex].userid = data.userid;
            firstarray[objIndex].ispresent = day.ispresent;
            firstarray[objIndex].manual_attendance_reason = day.manual_attendance_reason;
            firstarray[objIndex].absence_reason = day.absence_reason;
          }
        }
      });
    });    
    let amsubmisson_code = [];
    for(let j = 0 ;j<this.schedule_data.current_day ;j++){
      amsubmisson_code.push(1)
    } 

    var res = firstarray.filter(item1 => 
      !this.amreason_list.some(item2 => (item2.userid === item1.userid)))
    if(res.length == 0){
      $(".amackerror").css("display","none");
      let senddata = {
        "schedule_id" : this.sch_id,
        "absent_reason" : JSON.stringify(this.amreason_list),
        "am_acknowledgement" : JSON.stringify(amsubmisson_code)
      }
      this.loader = true;
      this.server.post("crtraining/amacknowledgement",senddata).then((data) => {
        this.loader = false;
        if (data.status == 200 && data.result.response == "success") {
          this.scoreuserlist = [];
          let msg2 = "AM Acknowledged successfully";
          this.confirm_pop.confirmPopups(msg2, (data) => {
            this.getdetails();
          this.router.navigateByUrl('trainingcourse/'+this.sch_id);
        })
        } else if (data.result.response == "failed") {
        }
      })
    }else{
      $(".amackerror").css("display","block");
    }
  }
  
 
  // onscoreChange(e,data){
  //   let score;
  //   let comments;
  //   if(data.score == ''){
  //     score = e.target.value;
  //   }else{
  //     score = data.score
  //   }
  //   if(data.remarks == ''){
  //     comments = e.target.value;
  //   }else{
  //     comments = data.remarks
  //   }
  //   let sendscoredata = {
  //     score : score,
  //     remarks : comments,
  //     userid : data.userid
  //   }
  //   if(this.scoreuserlist.length!=0){
  //     let objIndex = this.scoreuserlist.findIndex((obj => obj.userid == data.userid));
  //     if(objIndex == -1){
  //       this.scoreuserlist.push(sendscoredata)
  //     }else{
  //       this.scoreuserlist[objIndex].score = sendscoredata.score;
  //       this.scoreuserlist[objIndex].remarks = sendscoredata.remarks;  
  //     }
  //   }else{
  //     this.scoreuserlist.push(sendscoredata);
  //   }
  // }

  // onscore1Change(e,data,index){
  //   let score;
  //   let comments;
  //   if(index ==1){
  //     let sendscoredata = {
  //       score : e.target.value,
  //       remarks :  data.remarks != '' ? data.remarks : '',
  //       userid : data.userid
  //     }
  //     if(this.scoreuserlist.length!=0){
  //       let objIndex = this.scoreuserlist.findIndex((obj => obj.userid == data.userid));
  //       if(objIndex == -1){
  //         this.scoreuserlist.push(sendscoredata)
  //       }else{
  //         this.scoreuserlist[objIndex].score = sendscoredata.score;
  //       }
  //     }else{
  //       this.scoreuserlist.push(sendscoredata);
  //     }
  //   }else{
  //     let sendscoredata = {
  //       score : data.score != '' ? data.score : '',
  //       remarks : e.target.value,
  //       userid : data.userid
  //     }
  //     if(this.scoreuserlist.length!=0){
  //       let objIndex = this.scoreuserlist.findIndex((obj => obj.userid == data.userid));
  //       if(objIndex == -1){
  //         this.scoreuserlist.push(sendscoredata)
  //       }else{
  //         this.scoreuserlist[objIndex].remarks = sendscoredata.remarks;  
  //       }
  //     }else{
  //       this.scoreuserlist.push(sendscoredata);
  //     }
  //   }  
  // }
  // getTrainingCourseDetails(){
  //   this.server.get("trainer/training/"+this.sch_id)
  //     .then((data) => {
  //       if (data.status == 200 && data.result.response != 'failed'){
  //         this.training_detail = data.result.data;
  //         this.participant_data = data.result.data.participant;
  //       }
  //   })
  // }
  // addParticipant(){
  //   this.is_addparticipant = true;
  //   // this.participant_pop.showAddParticipant(this.sch_id, (data) => {
  //   // })
  // }
  // closenewrow(){
  //   this.addparticipantsmpin = "";
  //   this.is_addparticipant = false;
  // }
  // smpinvalidation(){
  //   this.addparticipantsmpin = "";
  //   this.is_addparticipant = false;
  //   this.server.post("trainer/smpinparticipant", {
  //     schedule_id:this.sch_id,
  //     smpin:this.addparticipantsmpin
  //   }).then((data) => {
  //     if (data.status == 200 && data.result.response == "success") {
  //       this.is_addparticipant = false;
  //       this.getTrainingCourseDetails();
  //     } else if (data.result.response == "failed") {
  //         this.confirm_pop.confirmPopups(data.result.message, (data) => {
  //           // this.router.navigateByUrl('trainer');
  //         }, (data)=>{
  //           // this.router.navigateByUrl('trainer');
  //         })
  //     }
  //   })
  // }
  // removeParticipant(item){
  //   let msg1 = "Are you sure want to remove the user";
  //   this.confirm_pop.confirmPopups(msg1, (data) => {
  //     this.server.post("trainer/removeparticipant", {
  //       schedule_id: this.sch_id,
  //       userid:item.userid
  //     }).then((data) => {
  //         if (data.status == 200 && data.result.response != 'failed'){
  //           this.getTrainingCourseDetails();
  //         }
  //     })
  //   }, (data)=>{
  //     // this.router.navigateByUrl('trainer');
  //   })
  // }
  // selectCheckbox(item, i){
  //   this.participant_data.forEach(function(data, index) {
  //     if(data.userid == item.userid){
  //        data.is_attendance=(data.is_attendance==0)?1:0;
  //       // (data.is_attendance == 0)?data.is_attendance = 1:data.is_attendance = 0;
  //     }
  //   });
  // }
  // onSave(){
  //   let msg1 =  "Are you sure want to save the training data";
  //   this.confirm_pop.confirmPopups(msg1, (data) => {
  //     this.server.post("trainer/training/"+this.sch_id, {
  //       participant_json: JSON.stringify(this.participant_data),
  //       is_save:1
  //     }).then((data) => {
  //       if (data.status == 200 && data.result.response == "success") {
  //         let msg2 = "The training course is submitted 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"){
  //         alert(data.result.message)
  //       }else{
  //         this.router.navigateByUrl('');
  //       }
  //     })
  //   }, (data)=>{
  //   })
    
  // }

  // onSubmit(){
  //   if(this.isValidTraining()){
  //     let msg1 = "Are you sure want to finish the training data";
  //     this.confirm_pop.confirmPopups(msg1, (data) => {
  //       this.server.post("trainer/training/"+this.sch_id, {
  //         participant_json: JSON.stringify(this.participant_data)
  //       }).then((data) => {
  //         if (data.status == 200 && data.result.response == "success") {
  //           let msg2 = "The training course is submitted 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"){
  //           alert(data.result.message)
  //         }else{
  //           this.router.navigateByUrl('');
  //         }
  //       })
  //     }, (data)=>{
  //     })
  //   }else{
  //     let msg = "Some of the fields are not yet completed";
  //     this.confirm_pop.confirmPopups(msg, (data) => {
  //     }, (data)=>{
        
  //     })
  //   }
  // }
  // isValidTraining(){
  //   let rval = true;
  //   this.participant_data.forEach(function(data, index) {
  //     if(rval){
  //       if(data.is_attendance==1){
  //         if(data.score>0){
  //           rval = true 
  //         }else{
  //           rval = false;
  //           return rval;
  //         }
  //       }else{
  //         if(data.score>0){
  //           rval = false
  //           return rval;
  //         }else{
  //           rval = true;
  //         }
  //         if(rval){
  //           if(data.remarks!=""){
  //             rval = false
  //             return rval;
  //           }else{
  //             rval = true;
  //           }
  //         }
  //       }
  //     }
  //   });
  //   return rval;
  // }

  

}
