import { Component, OnInit, OnDestroy } from '@angular/core';
import * as html2canvas from 'html2canvas';
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 { ActivatedRoute } from '@angular/router';
import { User } from '../../../../models/User';
import { Parrain } from '../../../../models/Parrain';
import { Commercant } from '../../../../models/Commercant';
import { FireImg } from '../../../../models/FireImg';
import { OperationCommerciale } from '../../../../models/OperationCommerciale';
import { CarteParrainage } from '../../../../models/CarteParrainage';
import { OpCommercialService } from '../../../services/opCommercial/op-commercial.service';
import { Subscription } from 'rxjs/Subscription';
import { AuthService } from '../../../services/auth/auth.service';
import { ToastrService } from '../../../typescripts/angular-bootstrap-md/pro';

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

  radioParrain: string;

  user: Observable<firebase.User>;
  localUser: any;
  parrain: Parrain;
  commercant: Commercant;
  opComm: OperationCommerciale;
  cartePar: CarteParrainage;
  birthdayTemp: Date;
  commList: FirebaseListObservable<any[]>;
  opCommList: FirebaseListObservable<any[]>;
  parrainExistList: FirebaseListObservable<any[]>;
  parrainAffList: FirebaseListObservable<any[]>;
  carteParList: FirebaseListObservable<any[]>;
  parSelect: string;
  selectPar: boolean;
  parrainAffListTemp = [];
  databaseRef: any;

  parrainsTest: Parrain[];
  filteredParrainsTest: any[];
  subscription: Subscription;

  validC: string;

  yearTest: number;

  minDateTimeTest: Date;
  maxDateTimeTest: Date;
  parrainDateTimeTest: Date;

  carteExitDeja: boolean;
  carteEnvoieOK: boolean;
  carteEnvoieEncours: boolean;
  echecRegisterPar: boolean;
  cartePars: any;
  filteredCartePars: any;

  filters = {};
  secondaryApp: any;
  constructor(public afAuth: AngularFireAuth, public afDb: AngularFireDatabase,
              private router: Router, private route: ActivatedRoute,
              private opComService: OpCommercialService, private toastrService: ToastrService) {
    this.user = afAuth.authState;
    this.carteExitDeja = false;
    this.carteEnvoieOK = false;
    this.echecRegisterPar = false;
    this.carteEnvoieEncours = false;
    this.filteredCartePars = {};
    this.radioParrain = '';
    this.validC = '';
    this.localUser = new User();
    this.parrain = new Parrain();
    this.commercant = new Commercant();
    this.cartePar = new CarteParrainage();
    this.cartePar.uid = firebase.database().ref().child('CarteParrainage').push().key;
    this.cartePar.historique = new Array();
    this.parrainAffList = null;
    this.minDateTimeTest = new Date('1917-01-01');
    this.maxDateTimeTest = new Date('2117-01-01');
    this.parrainDateTimeTest = new Date(this.parrain.birthday);
    this.yearTest = this.parrain.birthday.getFullYear();
    this.databaseRef = firebase.database().ref();

    const config = {apiKey: 'AIzaSyD2O5MxwZ4BRWvVc77FZliBvtj0pmcdzos',
      authDomain: 'webappparrain.firebaseapp.com',
      databaseURL: 'https://webappparrain.firebaseio.com',
      projectId: 'webappparrain',
      storageBucket: 'webappparrain.appspot.com',
      messagingSenderId: '808271162007'
    };
    this.secondaryApp = null;
    this.secondaryApp = firebase.apps.length <= 1 ? firebase.initializeApp(config, 'Secondary') : firebase.app('Secondary');


    this.user.subscribe(
      (auth) => {
        if (auth) {
          this.commList = this.afDb.list('/Commercant/', {
              query: {
                orderByChild: 'uid',
                equalTo: auth.uid.toString()
              }
            }
          );

          this.commList.forEach(commerc => {
            commerc.forEach(elementCommerc => {
              this.commercant = elementCommerc;
            });
          });
          // initialisation carte
          this.route.params.subscribe(params => {
            // this.test = params['idOp'];
            this.opCommList = this.afDb.list('/OperationCommercial/', {
                query: {
                  orderByChild: 'uid',
                  equalTo: params['idOp']
                }
              }
            );
            this.opCommList.forEach(op => {
              op.forEach(element => {
                this.opComm = element;

                this.cartePar.name = this.opComm.name;
                this.cartePar.commercantCarte = this.opComm.commercantOpCom;
                this.cartePar.operationCommercialCarte = this.opComm;
                this.cartePar.dateDebut = this.opComm.dateDebut;
                this.cartePar.dateFin = this.opComm.dateFin;

                const todayTemp = new Date(Date.now());
                const debutTemp = new Date(this.opComm.dateDebut);
                const finTemp = new Date(this.opComm.dateFin);

                if (todayTemp.getTime() >= debutTemp.getTime() && todayTemp.getTime() <= finTemp.getTime()) {
                  this.cartePar.status = 'Active';
                } else {
                  this.cartePar.status = 'Inactive';
                }
                this.cartePar.carteTemplate = this.opComm.carteTemplate;
              });
            });
            // fin initialisation carte
            // si parrain affilié
            this.carteParList = this.afDb.list('/CarteParrainage/', {
                query: {
                  orderByChild: 'operationCommercialCarte/uid',
                  equalTo: params['idOp']
                }
              }
            );
            this.carteParList.forEach(carte => {
              carte.forEach(elementCarte => {
                this.parrainAffList = this.afDb.list('/Parrain/', {
                    query: {
                      orderByChild: 'uid',
                      equalTo: elementCarte.parrainCarte.uid
                    }
                  }
                );
                this.parrainAffList.forEach(parAf => {
                  parAf.forEach(elementparAf => {
                    this.parrainAffListTemp.push(
                      {
                        uid : elementparAf.uid,
                        firstname : elementparAf.firstname,
                        familyname: elementparAf.familyname
                      });
                  });
                });
              });
            });
          });
          // fin si parrain affilié
          // si parrain exist non affilié
          this.parrainExistList = this.afDb.list('/Parrain/', {
              query: {
                orderByChild: 'uid'
              }
            }
          );
          // fin si parrain exist non affilié
        }
      }
    );
  }


//////
  filter(query: string) {
    this.filteredParrainsTest = (query) ?
      this.parrainsTest.filter(p => (p.firstname.toLowerCase() + p.familyname.toLowerCase()).includes(query.toLowerCase())) :
      [];
  }
//////

  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;
    }
  }


  regiPar(){
    let parrainTemp = new Parrain();
    this.carteEnvoieOK = false;
    this.parrain.status = 'Parrain';
    this.parrain.secretCode = this.getRandomArbitrary(1111, 9999).toString();
    this.parrain.password = this.getRandomArbitrary(111111, 999999).toString();
    parrainTemp = this.parrain;

    var parrainExistListTemp = this.afDb.list('/Parrain/', {
        query: {
          orderByChild: 'email',
          equalTo: this.parrain.email
        }
      }
    ).subscribe(tab => {
      if (tab.length === 0) {
        this.secondaryApp.auth().createUserWithEmailAndPassword(parrainTemp.email, parrainTemp.password)
          .catch(e => {
            this.carteEnvoieOK = false;
          })
          .then(function(userCreate) {
            if(userCreate){
              // I don't know if the next statement is necessary
              const imagePath = 'profilImage/' + userCreate.uid + '/userPic.jpg';
              const dbRef = firebase.database().ref();
              const userRef = dbRef.child('Parrain').child(userCreate.uid);
              userCreate.updateProfile({
                displayName: parrainTemp.status,
                photoURL: imagePath,
                emailVerified: true
              });
              try {
                parrainTemp.uid = userCreate.uid;
                parrainTemp.emailVerified = userCreate.emailVerified;
                userRef.set(parrainTemp);



              } catch (e) {
                // No content response..
                console.log(e);
                // this.goToOpComm();
                // this.router.navigate(['/']);
              }
            }

            // fin
          });


        const parNewlistTemp = this.afDb.list('/Parrain/', {
            query: {
              orderByChild: 'email',
              equalTo: parrainTemp.email
            }
          }
        );

        parNewlistTemp.forEach(par => {
          par.forEach(elementParTemp => {
            if (elementParTemp !== undefined && elementParTemp.email === parrainTemp.email) {
              if (elementParTemp.uid !== '') {
                this.getIdParrain(elementParTemp.uid);
                this.creerCartePar();
                this.carteEnvoieEncours = true;
                this.carteEnvoieOK = true;
                this.echecRegisterPar = false;
                this.secondaryApp.auth().sendPasswordResetEmail(elementParTemp.email);
                this.secondaryApp.auth().currentUser.sendEmailVerification();
                setTimeout(() => {
                    this.secondaryApp.auth().signOut();
                    this.carteEnvoieEncours = false;
                    this.goToOpComm();
                    this.toastrService.success('Envoie de la carte à ' + elementParTemp.familyname
                      + ' ' + elementParTemp.firstname);
                  },
                  3000);
              }
            }
          });
        });
      } else {
        this.carteEnvoieOK = false;
        this.echecRegisterPar = true;
      }
    });
  }

  getRandomArbitrary(min, max) {
    return Math.trunc(Math.random() * (max - min) + min);
  }
  initParSelect() {
    this.parSelect = '';
    this.parrain = new Parrain;
    this.birthdayTemp = new Date;
    this.echecRegisterPar = false;
  }

  getIdParrain(parUid) {
    this.carteEnvoieOK = false;
    this.carteExitDeja = false;
    const parlistTemp = this.afDb.list('/Parrain/', {
        query: {
          orderByChild: 'uid',
          equalTo: parUid
        }
      }
    );

    parlistTemp.forEach(par => {
      par.forEach(elementParTemp => {
        this.parrain = elementParTemp;
        this.cartePar.parrainCarte = elementParTemp;
      });
    });

    this.selectPar = true;

    if (this.radioParrain === 'Newparrain') {
      this.parSelect = ' : '
        + this.cartePar.parrainCarte.familyname + ' '
        + this.cartePar.parrainCarte.firstname;
    } else if (this.radioParrain === 'ParrainExist'){
      this.parrainExistList.forEach(parEx => {
        parEx.forEach(elementparEx => {
          if (elementparEx.uid === parUid){
            this.parSelect = ' : '
              + elementparEx.familyname + ' '
              + elementparEx.firstname;
          }
        });
      });
    }

  }

  carteExist(parUid) {
    if (this.parSelect !== '' && this.carteExitDeja === false){
      this.afDb.list('/CarteParrainage/', {
        query: {
          orderByChild: 'operationCommercialCarte/uid',
          equalTo: this.opComm.uid
        }}).subscribe(cartes => {

        this.cartePars = cartes;
        for (let i = 0; i < cartes.length; i++){
          if (cartes[i].parrainCarte.uid === parUid){
            this.carteExitDeja = true;
          }
        }
        if (this.carteExitDeja === false) {
          this.creerCartePar();
          this.carteEnvoieEncours = true;
          this.carteEnvoieOK = true;
          setTimeout(() => {
              this.carteEnvoieEncours = false;
              this.goToOpComm();
              this.toastrService.success('Envoie de la carte à ' + this.cartePar.parrainCarte.familyname
                + ' ' + this.cartePar.parrainCarte.firstname);
            },
            3000);
        } else {
          console.log('Error');
          // this.carteEnvoieOK = false;
        }
      });
    }
  }

  envoyerCartePar(){

    this.carteExist(this.cartePar.parrainCarte.uid);

  }
  creerCartePar() {
    this.sectionToImage(this.cartePar);
    this.opComm.nbEnvoie = ((+this.opComm.nbEnvoie) + 1).toString();

    const opEnvRef = this.databaseRef.child('OperationCommercial').child(this.opComm.uid.toString()).child('nbEnvoie');
    opEnvRef.set(this.opComm.nbEnvoie);

    this.validC = 'ok';

  }
  sectionToImage(maCarteP: CarteParrainage) {
    html2canvas(document.getElementById('subCard1'), {
      // allowTaint: true,
      useCORS: true,
      logging: true,
      onrendered: function (canvas) {
        const context = canvas.getContext('2d');
        const img = new Image();

        const offsets = document.getElementById('subCard1').getBoundingClientRect();
        const imgTop = offsets.top;
        const imgLeft = offsets.left;
        img.onload = function () {
          context.drawImage(img, imgLeft, imgTop, 1920, 1200);
        };
        img.crossOrigin = 'Anonymous';
        canvas.crossOrigin = 'Anonymous';

        canvas.id = 'canvas';
        canvas.toBlob(blob => {

          const nouvelleImg = new Image();
          const storageRef = firebase.storage().ref();
          nouvelleImg.setAttribute('crossOrigin', 'anonymous');
          nouvelleImg.src = blob;

          storageRef.child('CarteParrainage/' + maCarteP.uid + '/carteTemplate.jpg').put(blob).then((snapshot) => {
            const updates = {};
            maCarteP.carteTemplate.path = 'CarteParrainage/' + maCarteP.uid + '/carteTemplate.jpg';
            maCarteP.carteTemplate.filename = maCarteP.name;
            maCarteP.carteTemplate.downloadURL = snapshot.downloadURL;
            updates['CarteParrainage/' + maCarteP.uid] = maCarteP;
            firebase.database().ref().update(updates);
          });
        }, 'image/jpeg', 20);
      }
    });
  }

  goToOpComm() {
    this.router.navigate(['/opCommercial']);
  }
  //////
  ngOnInit() {
    this.subscription = this.opComService.getParrains()
      .subscribe(parrains => this.parrainsTest = parrains);
  }
//////

  ngOnDestroy() {
    this.secondaryApp.delete();
    this.validC = '';
    if (this.subscription) {
      this.subscription.unsubscribe();
    }

    this.radioParrain = '';
    this.cartePar = {
      uid: '',
      name: '',
      parrainCarte: new Parrain(),
      commercantCarte: new Commercant(),
      operationCommercialCarte: new OperationCommerciale(),
      dateDebut: new Date(),
      dateFin: new Date(),
      avantageCumule: '',
      avantageRecuperer: '',
      carteTemplate: new FireImg(),
      status: '',
      historique: []
    };
    this.localUser = {
      uid: '',
      image: new FireImg(),
      email: '',
      emailVerified: false,
      password: '',
      status: ''
    };
    this.parrain = {
      uid: '',
      image: new FireImg(),
      email: '',
      emailVerified: false,
      password: '',
      familyname: '',
      firstname: '',
      sex: '',
      birthday: new Date(),
      telephone: '',
      idCard: '',
      secretCode: '',
      status: ''
    };
  }
}
