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

import { Observable } from 'rxjs/Observable';
import { Router } from '@angular/router';
import { AngularFireDatabase, FirebaseListObservable } from 'angularfire2/database';
import * as firebase from 'firebase/app';
import { AngularFireAuth } from 'angularfire2/auth';
import { AuthService } from '../../../services/auth/auth.service';

import { User } from '../../../../models/User';
import { Parrain } from '../../../../models/Parrain';
import { Commercant } from '../../../../models/Commercant';

@Component({
  selector: 'app-edit-profil',
  templateUrl: './edit-profil.component.html',
  styleUrls: ['./edit-profil.component.scss'],
  providers: [AuthService]
})
export class EditProfilComponent implements OnInit, OnDestroy {

  user: Observable<firebase.User>;
  localUser: any;
  parrain: Parrain;
  commercant: Commercant;
  profileData: FirebaseListObservable<any[]>;
  imageProfil: string;
  modifiermdp: boolean;
  confirmOldPassword: string;
  newPassword: string;
  ConfirmPassword: string;
  minDateTimeTest: Date;
  maxDateTimeTest: Date;
  parrainDateTimeTest: Date;
  userCurrentFB: firebase.User;
  resetPassEmail: boolean;
  constructor(public afAuth: AngularFireAuth, public afDb: AngularFireDatabase,
              private router: Router, private authService: AuthService ) {
    this.resetPassEmail = false;
    this.localUser = new User();
    this.parrain = new Parrain();
    this.commercant = new Commercant();
    this.modifiermdp = false;
    this.confirmOldPassword = '';
    this.newPassword = '';
    this.ConfirmPassword = '';
    this.imageProfil = 'https://ssl.prcdn.com/uk/people/default-profile.png?1406639312';
    this.user = afAuth.authState;
    this.minDateTimeTest = new Date('1917-01-01');
    this.maxDateTimeTest = new Date('2117-01-01');
    this.parrainDateTimeTest = new Date(this.parrain.birthday);
    this.user.subscribe(
      (auth) => {
        if (auth) {
          this.userCurrentFB = auth;
          this.profileData = this.afDb.list('/' + auth.displayName + '/', {
              query: {
                orderByChild: 'uid',
                equalTo: auth.uid.toString()
              }
            }
          );
          this.profileData.forEach(utilisateur => {
            utilisateur.forEach(element => {
              if (auth.displayName === 'Parrain') {

                this.localUser = new Parrain();
                this.localUser = element;
                this.parrain = element;
                this.imageProfil = this.parrain.image.downloadURL;
              } else if (auth.displayName === 'Commercant') {
                this.localUser = new Commercant();
                this.localUser = element;
                this.commercant = element;
                this.imageProfil = this.commercant.image.downloadURL;
              }
            });
          });
        }
      }
    );
  }

  validationBirthday(){
    this.parrainDateTimeTest = new Date(this.parrain.birthday);
    if (this.parrainDateTimeTest.getTime() <= this.minDateTimeTest.getTime()
      || this.parrainDateTimeTest.getTime() >= this.maxDateTimeTest.getTime()) {
      return true;
    } else {
      return false;
    }
  }

  modifyPasswordSection() {
    if (this.modifiermdp === false) {
      this.modifiermdp = true;
    } else if (this.modifiermdp === true) {
      this.modifiermdp = false;
      this.confirmOldPassword = '';
      this.newPassword = '';
      this.ConfirmPassword = '';
    }
  }

  modifyProfile() {
    if (this.newPassword === '') {
      if (this.localUser.status === 'Parrain') {
        this.authService.modifyProfile(this.localUser, this.parrain, this.confirmOldPassword, this.userCurrentFB);
      } else if (this.localUser.status === 'Commercant') {
        this.authService.modifyProfile(this.localUser, this.commercant, this.confirmOldPassword, this.userCurrentFB);
      }
      this.goToProfil();
    } else {
      if (this.localUser.status === 'Parrain') {
        this.parrain.password = this.newPassword;
        this.authService.modifyProfile(this.localUser, this.parrain, this.confirmOldPassword, this.userCurrentFB);
      } else if (this.localUser.status === 'Commercant') {
        this.commercant.password = this.newPassword;
        this.authService.modifyProfile(this.localUser, this.commercant, this.confirmOldPassword, this.userCurrentFB);
      }
      this.goToProfil();
    }
  }
  resetPass() {
    if (this.localUser.status === 'Parrain') {
      if (this.parrain.email !== '') {
        firebase.auth().sendPasswordResetEmail(this.parrain.email);
        this.resetPassEmail = true;
      }
    } else if (this.localUser.status === 'Commercant') {
      if (this.commercant.email !== '') {
        firebase.auth().sendPasswordResetEmail(this.commercant.email);
        this.resetPassEmail = true;
      }
    }
  }
  goToProfil() {
    this.router.navigate(['/profil']);
  }
  ngOnDestroy(){}
  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;
        }
      });
    });

    try {
      this.user.subscribe(
        (auth) => {
          if (auth) {
            console.log(auth.uid);
          } else {
            // this.router.navigate(['/']);
          }
        });
    } catch (e) {
      // No content response..
      console.log(e);
      // this.router.navigate(['/']);
    }
  }

}
