import { Component, OnInit, OnDestroy } from '@angular/core';
import { Router } from '@angular/router';

import { AuthService } from '../../services/auth/auth.service';
import { User } from '../../../models/User';
import { Parrain } from '../../../models/Parrain';
import { Commercant } from '../../../models/Commercant';
import { FireImg } from '../../../models/FireImg';

@Component({
  selector: 'app-register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.scss'],
  providers: [AuthService]
})
export class RegisterComponent implements OnInit, OnDestroy {
  currentUser: User;
  parrain: Parrain;
  commercant: Commercant;
  ConfirmPasswordParrain: String;
  ConfirmPasswordCommercant: String;
  test: boolean;
  minDateTimeTest: Date;
  maxDateTimeTest: Date;
  parrainDateTimeTest: Date;
  fileCom: boolean;
  filePar: boolean;
  echecRegisterPar: boolean;
  echecRegisterCom: boolean;
  validationBirthdayP: boolean;
  constructor(private router: Router, private authService: AuthService) {
    this.fileCom = true;
    this.filePar = true;
    this.validationBirthdayP = true;
    this.echecRegisterPar = false;
    this.echecRegisterCom = false;
    this.currentUser = new User();
    this.parrain = new Parrain();
    this.commercant = new Commercant();
    this.test = false;
    this.minDateTimeTest = new Date('1917-01-01');
    this.maxDateTimeTest = new Date('2117-01-01');
    this.parrainDateTimeTest = new Date(this.parrain.birthday);
  }


  fileOKCom() {
    this.fileCom = false;
  }

  fileOKPar() {
    this.filePar = false;
  }

  keyDownFunctionParrain(event) {
    if (event.keyCode === 13) {
      // rest of your code
      if (this.parrain.email !== '' && this.parrain.password !== ''
        && (this.parrain.password === this.ConfirmPasswordParrain)
        && this.parrain.familyname !== '' && this.parrain.firstname !== ''
        && this.parrain.sex !== '' && this.parrain.telephone !== ''
        && (<HTMLInputElement>document.getElementById('orangeForm-File')).value !== '') {
        this.register();
      }
    }
  }

  keyDownFunctionCommercant(event) {
    if (event.keyCode === 13) {
      // rest of your code
      if (this.commercant.email !== '' && this.commercant.password !== ''
        && (this.commercant.password === this.ConfirmPasswordCommercant)
        && this.commercant.commercialName !== '' && this.commercant.raisonSociale !== ''
        && this.commercant.siret !== '' && (<HTMLInputElement>document.getElementById('orangeForm-File')).value !== '') {
        this.register();
      }
    }
  }

  register() {

    if (this.currentUser.status === 'Parrain') {
      this.parrain.status = this.currentUser.status;
      this.parrain.secretCode = this.getRandomArbitrary(1111, 9999).toString();
      this.authService.signUp(this.parrain).catch(e => {
        this.echecRegisterPar = true;
        this.test = false;
      });
      this.echecRegisterPar = false;
      this.test = true;
    }else if (this.currentUser.status === 'Commercant') {
      this.commercant.status = this.currentUser.status;
      let dateTemp = new Date(Date.now());
      this.commercant.dateInscription = new Date(dateTemp);
      this.authService.signUp(this.commercant).catch(e => {
        this.echecRegisterCom = true;
        this.test = false;
      });
      this.echecRegisterCom = false;
      this.test = true;
    }

  }

  clean() {
    this.ngOnDestroy();
    this.currentUser.status = '';
    this.test = false;
  }

  // On renvoie un nombre aléatoire entre une valeur min (incluse)
  // et une valeur max (exclue)
  getRandomArbitrary(min, max) {
    return Math.trunc(Math.random() * (max - min) + min);
  }

  validationBirthdayParrain(){
    let dateTempB = new Date(Date.now());
    this.parrainDateTimeTest = new Date(this.parrain.birthday);

    if (this.parrainDateTimeTest.getFullYear() > this.minDateTimeTest.getFullYear()
      && (this.parrainDateTimeTest.getFullYear() !== dateTempB.getFullYear())
      && this.parrainDateTimeTest.getFullYear() < this.maxDateTimeTest.getFullYear()
      && this.parrainDateTimeTest.getFullYear() !== NaN){

      if (!isNaN(this.parrainDateTimeTest.getTime())){

        this.validationBirthdayP = false;

      }else{

        this.validationBirthdayP = true;

      }
    }else{

      this.validationBirthdayP = true;

    }
  }

  ngOnInit() {
    var inputs = document.querySelectorAll( '.inputfile' );
    Array.prototype.forEach.call( inputs, function( input )
    {
      var label	 = input.nextElementSibling,
        labelVal = label.innerHTML;

      input.addEventListener( 'change', function( e )
      {
        var fileName = '';
        if( this.files && this.files.length > 1 ){
          fileName = ( this.getAttribute( 'data-multiple-caption' ) || '' ).replace( '{count}', this.files.length );
        }
        else {
          fileName = e.target.value.split( '\\' ).pop();
        }

        if( fileName ) {
          label.querySelector( 'span' ).innerHTML = fileName;
        }
        else {
          label.innerHTML = labelVal;
        }
      });
    });
  }

  ngOnDestroy() {
    this.test = false;
    this.ConfirmPasswordParrain = '';
    this.ConfirmPasswordCommercant = '';
    this.currentUser = {
      uid: '',
      image: new FireImg(),
      email: '',
      emailVerified: false,
      password: '',
      status: this.currentUser.status
    };
    this.parrain = {
      uid: '',
      image: new FireImg(),
      email: '',
      emailVerified: false,
      password: '',
      familyname: '',
      firstname: '',
      sex: '',
      birthday: new Date(),
      telephone: '',
      idCard: '',
      secretCode: '',
      status: ''
    };
    this.commercant = {
      uid : '',
      image: new FireImg(),
      raisonSociale : '',
      commercialName : '',
      siret : '',
      email : '',
      emailVerified : false,
      password : '',
      dateInscription : new Date(),
      status : ''
    };

  }
}
