import { Injectable, Input } from '@angular/core';
import { Router } from '@angular/router';

import * as firebase from 'firebase/app';
import { AngularFireAuth } from 'angularfire2/auth';

import { AngularFireDatabase, FirebaseListObservable } from 'angularfire2/database';

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


@Injectable()
export class AuthService {
  databaseRef: any;
  parrain: Parrain;
  commercant: Commercant;
  utilisateur: any;
  test: string;

  profileData: FirebaseListObservable<any[]>;
  profileDataParrain: FirebaseListObservable<any[]>;
  profileDataCommercant: FirebaseListObservable<any[]>;

  authState: firebase.User;
  @Input() folder: string;

  constructor(private afAuth: AngularFireAuth, private afDb: AngularFireDatabase, private router: Router) {
    this.parrain = new Parrain();
    this.commercant = new Commercant();

    afAuth.authState.subscribe(
      (auth) => {
          this.authState = auth;
      });
    this.databaseRef = firebase.database().ref();
  }

  get authenticated(): boolean {
    return this.authState !== null;
  }

  saveInfo(user: firebase.User, infoUser: any): boolean {
    if (infoUser.status === 'Parrain') {
      const userRef = this.databaseRef.child('Parrain').child(infoUser.uid);
      userRef.set(infoUser);
      return true;
    }else if (infoUser.status === 'Commercant') {
      var dateTemp = new Date(Date.now());
      infoUser.dateInscription = dateTemp;
      const userReff = this.databaseRef.child('Commercant').child(infoUser.uid);
      userReff.set(infoUser);
      const dateInsReff = this.databaseRef.child('Commercant').child(infoUser.uid).child('dateInscription');
      dateInsReff.set(dateTemp.toString());
      return true;
    }else {
      return false;
    }
  }

// oublie pas de MAJ emailVerified dans database
  signIn(email: string, password: string) {
    return firebase.auth().signInWithEmailAndPassword(email, password)
      .catch(e => {
        return e;
      })
      .then(user => {
      if (user ) {

        this.profileDataParrain = this.afDb.list('/Parrain/', {
            query: {
              orderByChild: 'uid',
              equalTo: user.uid.toString()
            }
          }
        );
        this.profileDataParrain.subscribe(snapshot => {
          if (snapshot.length > 0) {
            this.profileDataParrain.forEach(Parrain => {
              Parrain.forEach(elementParrain => {
                this.parrain = elementParrain;
                this.utilisateur = elementParrain;
                if (user.emailVerified){

                  firebase.auth().onAuthStateChanged(function (userUpdate) {
                    if (userUpdate !== null){
                      userUpdate.updateProfile({
                        displayName: elementParrain.status,
                        photoURL: elementParrain.image.downloadURL
                      });
                    }
                  });
                  if (this.utilisateur.status === 'Parrain') {
                    if (password !== this.parrain.password) {
                      const passWRef = this.databaseRef.child('Parrain').child(this.parrain.uid).child('password');
                      passWRef.set(password);
                    }
                    this.router.navigate(['/carteParrainageComponent']);
                  } else if (this.utilisateur.status === 'Commercant') {
                    this.router.navigate(['/opCommercial']);
                  }
                }else{
                  console.log('email non verifié!!');
                }
              });
            });
          }
        });
        this.profileDataCommercant = this.afDb.list('/Commercant/', {
            query: {
              orderByChild: 'uid',
              equalTo: user.uid.toString()
            }
          }
        );
        this.profileDataCommercant.subscribe(snapshot => {
          if (snapshot.length > 0) {
            this.profileDataCommercant.forEach(Commercant => {
              Commercant.forEach(elementCommercant => {
                this.commercant = elementCommercant;
                this.utilisateur = elementCommercant;
                if (user.emailVerified){
                  firebase.auth().onAuthStateChanged(function (userUpdate) {
                    if (userUpdate !== null){
                      userUpdate.updateProfile({
                        displayName: elementCommercant.status,
                        photoURL: elementCommercant.image.downloadURL
                      });
                    }
                  });
                  if (this.utilisateur.status === 'Parrain') {
                    this.router.navigate(['/carteParrainageComponent']);
                  } else if (this.utilisateur.status === 'Commercant') {
                    if (password !== this.parrain.password) {
                      const passWRef = this.databaseRef.child('Commercant').child(this.commercant.uid).child('password');
                      passWRef.set(password);
                    }
                    this.router.navigate(['/opCommercial']);
                  }
                }else{
                  console.log('email non verifié!!');
                }
              });
            });
          }
        });

        if (user.email === 'webapp.xjc@gmail.com') {
          this.router.navigate(['/demandeOpCommercialAdmin']);
        }
      }else {
        console.log('Error');
      }
    });
  }

  signUp(infoUser: any) {
    return firebase.auth().createUserWithEmailAndPassword(infoUser.email, infoUser.password)
      .catch(e => {
        return e;
      })
      .then(userCreate => {
      userCreate.sendEmailVerification();
      infoUser.uid = userCreate.uid;

      if (this.saveInfo(userCreate, infoUser)) {
        if (this.upload(infoUser)) {
          console.log('');
        }else {
          console.log('Error');
        }
      }else {
        console.log('Error');
      }

    });
  }


  logout() {
    firebase.auth().signOut();
  }


  upload(info: any): boolean {
    const storageRef = firebase.storage().ref();
    this.folder = '/' + info.status + '/' + info.uid + '/image';

    for (const selectedFile of [(<HTMLInputElement>document.getElementById('orangeForm-File')).files[0]]) {
      const folder = this.folder;
      const path = `${this.folder}`;
      const iRef = storageRef.child(path);

      iRef.put(selectedFile).then((snapshot) => {
        const updates = {};
        info.image.path = path;
        info.image.filename = 'Profil picture';
        info.image.downloadURL = snapshot.downloadURL;
        updates[folder] = info.image;
        firebase.database().ref().update(updates);
      });
    }
    firebase.auth().onAuthStateChanged(function (userUpdate) {
      if (userUpdate !== null){
        userUpdate.updateProfile({
          displayName: info.status,
          photoURL: info.image.downloadURL
        });
      }
    });
    return true;
  }

  uploadModify(info: any) {
    const storageRef = firebase.storage().ref();
    this.folder = '/' + info.status + '/' + info.uid + '/image';

    for (const selectedFile of [(<HTMLInputElement>document.getElementById('orangeForm-File')).files[0]]) {
      const folder = this.folder;
      const path = `${this.folder}`;
      const iRef = storageRef.child(path);
      if(selectedFile !== undefined){
        try{
          iRef.put(selectedFile).then((snapshot) => {
            const updates = {};
            info.image.path = path;
            info.image.filename = 'Profil picture';
            info.image.downloadURL = snapshot.downloadURL;
            updates[folder] = info.image;
            firebase.database().ref().update(updates);
          });
        }catch (e){
          console.log('Error: ' + e);
        }

      }
    }
    firebase.auth().onAuthStateChanged(function (userUpdate) {
      if (userUpdate !== null){
        userUpdate.updateProfile({
          displayName: info.status,
          photoURL: info.image.downloadURL
        });
      }
      if (userUpdate) {
        console.log('');
      } else {
        console.log('Error');
      }

    });
  }

  modifyProfile(user: User, infoUser: any, confirmOldPassword: string, userCurrentFB: firebase.User) {
    if (infoUser.status === 'Parrain') {
      const userRef = this.databaseRef.child('Parrain').child(user.uid);
      const parrainTemp = user;
      infoUser.uid = user.uid;

      try {
        userRef.update(infoUser);
        this.uploadModify(infoUser);
        firebase.auth().onAuthStateChanged(function (userUpdate) {
          if (userUpdate) {
            console.log('');
            /*
            if (userCurrentFB.email !== infoUser.email){
              console.log('email diferrent ');
              userUpdate.updateEmail(infoUser.email);
            }
            if (confirmOldPassword !== infoUser.password) {
              console.log('mdp diferrent ');

              console.log('update: ' + infoUser.password);
              const passWRef = firebase.database().ref().child('Parrain').child(parrainTemp.uid).child('password');
              passWRef.set(infoUser.password);
              userUpdate.updatePassword(infoUser.password);
            }*/
          } else {
            console.log('Error');
          }

        });
      }catch (e){
        console.log('Error: ' + e);
      }
    }else if (infoUser.status === 'Commercant') {
      const userReff = this.databaseRef.child('Commercant').child(user.uid);
      infoUser.uid = user.uid;
      const commercantTemp = user;
      try {
        userReff.update(infoUser);
        this.uploadModify(infoUser);
        firebase.auth().onAuthStateChanged(function (userUpdate) {
          if (userUpdate) {

            /*
            if (userCurrentFB.email !== infoUser.email){
              console.log('email diferrent ');
              userUpdate.updateEmail(infoUser.email);
            }*/
            /*if (confirmOldPassword !== infoUser.password) {
              console.log('mdp diferrent ');
              const passWRef = firebase.database().ref().child('Commercant').child(commercantTemp.uid).child('password');
              passWRef.set(infoUser.password);
              userUpdate.updatePassword(infoUser.password);
            }*/
            console.log('');
          } else {
            console.log('Error');
          }

        });
      } catch (e) {
        console.log('Error: ' + e);
      }

    }

  }

}
