import { Component, Input, EventEmitter, Output } from "@angular/core";
import { FormGroup, FormControl, Validators } from "@angular/forms";
import { AuthService } from '../services/auth.service';
import { environment } from '../../environments/environment.dev';
import { IMyDrpOptions } from "mydaterangepicker";
import { LocalStorageService } from 'angular-2-local-storage';
import { ENTER } from '@angular/cdk/keycodes';
import {MatChipInputEvent} from '@angular/material';
import { Router } from '@angular/router';
import _ from "lodash";

@Component({
  selector: 'signup-as-student',
  templateUrl: '/signupasstudent.component.html',
  styleUrls: ['/signupasstudent.component.scss']
})

export class SignUpAsStudentComponent {

  @Input() email: string = '';
  @Output() signUpAsStudentSuccess = new EventEmitter<string>();
  firstFormGroup;
  secondFormGroup;
  thirdFormGroup;
  phoneregex: RegExp = /^(?:(?:\+|0{0,2})91(\s*[\-]\s*)?|[0]?)?[0123456789]\d{9}$/;
  emailFormControl = new FormControl('', [
    Validators.required,
    Validators.email,
  ]);
  phoneFormControl = new FormControl('', [
    Validators.required,
    Validators.pattern(this.phoneregex),
  ]);
  isLinear = false;
  firstNameError: boolean = false;
  lastNameError: boolean = false;
  institutionError: boolean = false;
  aadhaarError: boolean = false;
  loginemailErrMsg = '';
  phoneErrMsg = '';
  firstNameErrMsg = '';
  lastNameErrMsg = '';
  institutionErrMsg = '';
  isPwdError = false;
  isConfirmPwdError = false;
  tenthError: boolean = false;
  twelError: boolean = false;
  tenthErrMsg = '';
  twelErrMsg = '';
  priSkillError: boolean = false;
  secSkillError: boolean = false;
  birthdayErr: boolean = false;
  birthdayErMsg = ''
  OverallErrMsg = '';
  secSkillErrMsg = '';
  priSkillErrMsg = '';
  isError: boolean = false;
  isSuccess: boolean = false;
  isLoading: boolean = false;
  isEmailError: boolean = false;
  isPhonerror: boolean = false;
  OverallError: boolean = false;
  comPwdErrMsg = '';
  PwdErrMsg = '';
  successMessage = '';
  error: any;
  respData: any;
  showsignup: boolean = false;
  institutes: any;
  genders: string[] = ["Male", "Female", "Other"];
  sems: string[] = ["1st", "2nd", "3rd", "4th", "5th", "6th", "7th", "8th"];
  idtypes: string[] = ["Aadhaar", "College ID"];
  idDefault: string = "Aadhaar";
  imgUrl = environment.imageUrl;
  erroDiv: boolean = false;
  hide = true;
  myDateRangePickerOptions: IMyDrpOptions = {
    // other options...
    dateFormat: 'dd.mm.yyyy',
    disableSince: { year: 2005, month: 9, day: 22 },
    alignSelectorRight: true,
    openSelectorOnInputClick: true
  };
  locations: any[];
  selectedCollege: any;
  selectedCityofCollege: any;

  // pwdPattern = "^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?!.*\s).{6,12}$";
  mobnumPattern = /^(?:(?:\+|0{0,2})91(\s*[\-]\s*)?|[0]?)?[0123456789]\d{9}$/;
  emailPattern = /^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@(([0-9a-zA-Z])+([-\w]*[0-9a-zA-Z])*\.)+[a-zA-Z]{2,9})$/
  percentagePattern = /^\d+(\.\d{1,2})?$/;
  onlyText = /^[a-zA-Z ]*$/;
  readonly separatorKeysCodes: number[] = [ENTER];
  primarySkills: any[] = [];
  constructor(private AuthService: AuthService, private localStorageService: LocalStorageService, private router: Router) {
    this.firstFormGroup = new FormGroup({
      firstName: new FormControl('', [Validators.required, Validators.pattern(this.onlyText)]),
      lastName: new FormControl('', [Validators.required, Validators.pattern(this.onlyText)]),
      email: new FormControl('', [Validators.required, Validators.email]),
      password: new FormControl('', [Validators.required, Validators.minLength(6)]),
      confirm_password: new FormControl('', [Validators.required, Validators.minLength(6)]),
      phonenumber: new FormControl('', [Validators.required]),
      birthday: new FormControl('', Validators.required),
      gender: new FormControl('', Validators.required),
      nationality: new FormControl('', Validators.required),
      govType: new FormControl(''),
      govtId: new FormControl(''),
      college: new FormControl('', Validators.required),
      location: new FormControl({ value: this.selectedCityofCollege, disabled: true }, Validators.required),
      othercollege: new FormControl(),
      course: new FormControl('', Validators.required),
      currentSem: new FormControl('', Validators.required),
      overallPercentage: new FormControl('', [Validators.required, Validators.max(100),Validators.min(0), Validators.pattern(this.percentagePattern)]),
      twelPercentage: new FormControl('', [Validators.required, Validators.max(100),Validators.min(0), Validators.pattern(this.percentagePattern)]),
      tenthPercentage: new FormControl('', [Validators.required, Validators.max(100),Validators.min(0), Validators.pattern(this.percentagePattern)]),
      primarySkill: new FormControl('', Validators.required),
      secondarySkill: new FormControl('', Validators.required)
    });
    this.firstFormGroup.patchValue({
      'email': this.localStorageService.get('emailForSignUp')
    });
    this.getAvlbColleges();
  }

  ngOnInit() {
    console.log("page On inti only");
    this.firstFormGroup.patchValue({
      'email': this.localStorageService.get('emailForSignUp')
    });
    this.locations = ['Chennai', 'Vellore', 'Coimbatore', 'Mysore', 'Pune', 'Bengaluru'];

  }
  getAvlbColleges() {
    this.AuthService.getAllColleges().then(resp => {
      if (!resp.error) {
        this.institutes = resp.collegeList;
      }
      else {
        console.log("error in fetching colleges")
      }
    })
  }

  studentSignup() {

      this.isError = false;
      this.isSuccess = false;
      this.isConfirmPwdError = false;
        var tempPriSkill;
        _.each(this.primarySkills, (skill)=>{
          if(tempPriSkill) {
           tempPriSkill = tempPriSkill + ',' + skill.name;
          }else {
            tempPriSkill = skill.name
          }
           
       });
       var requestObj = {
         userName: this.firstFormGroup.value.email,
         firstName: this.firstFormGroup.value.firstName,
         lastName: this.firstFormGroup.value.lastName,
         email: this.firstFormGroup.value.email,
         phone: this.firstFormGroup.value.phonenumber,
         password: this.firstFormGroup.value.password,
         location: this.selectedCityofCollege,
         birthday: this.firstFormGroup.value.birthday.jsdate.toISOString(),
         gender: this.firstFormGroup.value.gender,
         nationality: this.firstFormGroup.value.nationality,
         govType: this.firstFormGroup.value.govType,
         govId: this.firstFormGroup.value.govtId,
         institution: this.firstFormGroup.value.college,
         course: this.firstFormGroup.value.course,
         currentSem: this.firstFormGroup.value.currentSem,
         overallPercentage: this.firstFormGroup.value.overallPercentage,
         xiiPercentage: this.firstFormGroup.value.twelPercentage,
         xPercentage: this.firstFormGroup.value.tenthPercentage,
         priSkills: tempPriSkill,
         secSkills: this.firstFormGroup.value.secondarySkill
       }
       this.AuthService.studentUnifiedSignUp(requestObj).then( (resp: any)=>{
         console.log(resp);
         if(resp.successMessage) {
           this.successMessage = resp.successMessage;
           this.isSuccess = true;
           setTimeout(() => {
            this.router.navigate(['']);
           }, 4000);
           
         }else if(resp.status === 'error') {
           this.isError = true;
           this.error = resp.message;
         }
         console.log('success take him to login')
       })
     
    }

  onDateChanged(evnt) {
    console.log(evnt)
  }

  ngOnDestroy() {
   // this.signUpAsStudentSuccess.unsubscribe();
  }

  onCollegeSelect(e) {
    console.log(e);
    this.selectedCollege = e.value;
    console.log(this.selectedCollege);
    console.log(this.institutes);
    this.institutes.forEach(element => {
      if (this.selectedCollege == element.collegeName) {
        this.selectedCityofCollege = element.city;
        this.firstFormGroup.patchValue({
          'location': element.city
        });
      }
    });
  }

  add(event: MatChipInputEvent): void {
    const input = event.input;
    const value = event.value;

    // Add our fruit
    if ((value || '').trim()) {
      this.primarySkills.push({ name: value.trim() });
    }

    // Reset the input value
    if (input) {
      input.value = '';
    }
  }

  remove(fruit: any): void {
    const index = this.primarySkills.indexOf(fruit);

    if (index >= 0) {
      this.primarySkills.splice(index, 1);
    }
  }

  goBackToLogin() {
    this.router.navigate(['']);
  }

  validateConfirmPassword() {
    console.log('coming in validate password');
    if(this.firstFormGroup.value.password !== this.firstFormGroup.value.confirm_password) {
      console.log('password does not match');
      this.isConfirmPwdError = true;
      this.comPwdErrMsg = "Password mismatched.";
    }else {
      this.isConfirmPwdError = false;
      this.comPwdErrMsg = "";
    }
  }
}