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 { Location } from '@angular/common';
import { FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms';
import { DatepickerOptions } from 'ng2-datepicker';

@Component({
  selector: 'app-addbatch',
  templateUrl: './addbatch.component.html',
  styleUrls: ['./addbatch.component.scss']
})
export class AddbatchComponent 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;
  registerForm: FormGroup;
  showtextbox;
  submitted;
  options: DatepickerOptions = {
    minDate: new Date(Date.now()), // Minimal selectable date
  }
  constructor(private server: HyperService ,private formBuilder: FormBuilder, private router: Router, private route: ActivatedRoute,private _location: Location) {
    this.sub = this.route.params.subscribe(params => {
      this.sch_id = params['id'];
      this.type = params['type'];
      this.user_id = params['token'];
      this.userData.emailid = params['email'];
      this.rmmail = params['rmmail'];
      this.ammail = params['ammail'];
      this.zmmail = params['zmmail'];
    });
  }

  ngOnInit() {
    this.registerForm = this.formBuilder.group({
      title: ['', Validators.required],
      description: ['', Validators.required],
      // customer_mobile: ['', [Validators.required, Validators.pattern(/^[0-9]{10,10}$/)]],
      // customer_name: ['', Validators.required],
      startdate: [new Date(),Validators.required],
      enddate : [new Date(),Validators.required],
      startTime : ['',Validators.required],
      endTime : ['',Validators.required]
    });
    LocalStorage.setValue('is_firsttime', false);
    this.getTrainingCourseDetails();
  }
  backclicked(){
    this._location.back();
  }
  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)=>{
    })
    
  }
  onCancel(){
    if(this.type!="mobile"){
      this.router.navigateByUrl('trainer');
    }else{
      this.router.navigateByUrl('trainer/' +this.type+'/'+this.userData.emailid+'/'+this.user_id);
    }
    
  }
  onSubmit(val){
    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;
  }

}
