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 { ActivatedRoute } from '@angular/router';
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 { Filleul } from '../../../../models/Filleul';
import { Scan } from '../../../../models/Scan';
import { ToastrService } from '../../../typescripts/angular-bootstrap-md/pro';
import { Admin } from '../../../../models/Admin';


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

  filleulSelect: string;
  ParrainCarteSelect: string;
  carteParSelected: string;
  radioFilleul: string;
  user: Observable<firebase.User>;
  localUser: any;
  filleul: Filleul;
  scan: Scan;
  parrain: Parrain;
  commercant: Commercant;
  opComm: OperationCommerciale;
  cartePar: CarteParrainage;

  avAdmin: string;

  commList: FirebaseListObservable<any[]>;
  opCommList: FirebaseListObservable<any[]>;
  scanList: FirebaseListObservable<any[]>;
  adminAvantage: FirebaseListObservable<any[]>;
  filleulExistList: FirebaseListObservable<any[]>;
  adminData: FirebaseListObservable<any[]>;
  admin: Admin;
  databaseRef: any;

  filleulTest: Filleul[];
  carteTest: CarteParrainage[];
  filteredFilleulsTest: any[];
  filteredCartesTest: any[];
  filleulListTemp  = [];
  subscription: Subscription;
  subscriptionCarte: Subscription;
  isFilleulAnonyme: boolean;

  constructor(public afAuth: AngularFireAuth, public afDb: AngularFireDatabase,
              private router: Router, private opComService: OpCommercialService,
              private route: ActivatedRoute, private toastrService: ToastrService) {
    this.admin = new Admin();
    this.isFilleulAnonyme = false;
    this.radioFilleul = '';
    this.filleulSelect = '';
    this.ParrainCarteSelect = '';
    this.carteParSelected = '';
    this.avAdmin = '';
    this.filleul = new Filleul();
    this.scan = new Scan();
    this.parrain = new Parrain();
    this.commercant = new Commercant();
    this.cartePar = new CarteParrainage();
    this.filleulExistList = null;
    this.user = afAuth.authState;
    this.databaseRef = firebase.database().ref();
    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.opCommList = this.afDb.list('/OperationCommercial/', {
                query: {
                  orderByChild: 'uid',
                  equalTo: params['idOp']
                }
              }
            );
            this.opCommList.forEach(op => {
              op.forEach(element => {
                this.opComm = element;
                this.subscriptionCarte = this.opComService.getCartesOP(element.uid)
                  .subscribe(cartes => this.carteTest = cartes);
                this.scanList = this.afDb.list('/Scan/', {
                  query: {
                    orderByChild: 'operationCommercial/uid',
                    equalTo: params['idOp']
                  }
                });
              });
            });
          });
          // fin si parrain affilié
          // si parrain exist non affilié
          this.filleulExistList = this.afDb.list('/Parrain/', {
              query: {
                orderByChild: 'uid'
              }
            }
          );
          this.filleulExistList.forEach(fill => {
            fill.forEach(elementfillAf => {
              this.filleulListTemp.push(
                {
                  uid: elementfillAf.uid,
                  firstname: elementfillAf.firstname,
                  familyname: elementfillAf.familyname
                });
            });
          });
          // fin si parrain exist non affilié
          this.adminData = this.afDb.list('/Admin/', {
              query: {
                orderByChild: 'uid'
              }
            }
          );
          this.adminData.forEach(avantage => {
            avantage.forEach(elementavantage => {
              this.admin = elementavantage;
            });
          });
        }
      }
    );

  }
  goToOpComm() {
    this.router.navigate(['/opCommercial']);
  }
  filterCarte(query: string) {
    this.filteredCartesTest = (query) ?
      this.carteTest.filter(c => (c.parrainCarte.firstname.toLowerCase()
        + c.parrainCarte.familyname.toLowerCase()).includes(query.toLowerCase())) :
      [];
  }
  filter(queryF: string) {
    this.filteredFilleulsTest = (queryF) ?
      this.filleulTest.filter(f => (f.firstname.toLowerCase() + f.familyname.toLowerCase()).includes(queryF.toLowerCase())) :
      [];
  }

  scanCarteFil() {

    this.scan.uid = firebase.database().ref().child('Scan').push().key;
    this.scan.dateCreation = new Date (Date.now());
    this.scan.carteParrainID = this.cartePar.parrainCarte.uid;
    this.scan.carteFilleulID = this.filleul.idCard;
    this.scan.operationCommercial = this.opComm;
    this.scan.valeurParrain = this.opComm.avantageParrain;
    this.scan.valeurFilleul = this.opComm.avantageFilleul;
    const userRef = this.databaseRef.child('Scan').child(this.scan.uid);
    userRef.set(this.scan);

    this.updateCarte();
    this.goToOpComm();
    this.toastrService.success('Scan du filleul ' + this.filleul.familyname + ' ' + this.filleul.firstname);
  }

  filleulAnonymous() {
    this.isFilleulAnonyme = true;
    this.filleulSelect = 'Filleul anonyme';
    this.filleul = new Filleul();
  }

  updateCarte() {

    this.cartePar.avantageCumule = ((+this.cartePar.avantageCumule) + (+this.opComm.avantageParrain)).toString();

    const carteRef = this.databaseRef.child('CarteParrainage').child(this.cartePar.uid.toString()).child('avantageCumule');
    carteRef.set(this.cartePar.avantageCumule);


    this.opComm.nbScan = ((+this.opComm.nbScan) + 1).toString();

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

    // Admin
    this.adminAvantage = this.afDb.list('/Admin/', {
        query: {
          orderByChild: 'avantageCumule'
        }
      }
    );
    this.adminAvantage.forEach(avantage => {
      avantage.forEach(elementavantage => {
          this.avAdmin = elementavantage;
      });
    });
    this.admin.avantageCumule = ((+this.admin.avantageCumule) + (+this.opComm.avantageParrain)).toString();
    //this.avAdmin = ((+this.avAdmin) + (+this.opComm.avantageParrain)).toString();

    const adminAvantageRef = this.databaseRef.child('Admin').child(this.admin.uid).child('avantageCumule');
    adminAvantageRef.set(this.admin.avantageCumule);

    //Fin Admin

    //Historique carte

    var elementCarteHist = 'Le ' + (this.scan.dateCreation).getDate() + '/' + (this.scan.dateCreation).getMonth()
      + '/' + (this.scan.dateCreation).getFullYear() + ' à ' + (this.scan.dateCreation).getHours() + ':'
      + (this.scan.dateCreation).getMinutes() + ', ' + ' la visite de '
      + (this.filleul.familyname === '' ? 'Filleul' : this.filleul.familyname.toUpperCase())
      + ' ' + (this.filleul.firstname === '' ? 'anonyme' : this.filleul.firstname.toUpperCase())
      + ' a credité cette carte de ' + this.opComm.avantageParrain
      + '€ supplémentaires, à valoir lors d un prochain achat.';
    // this.cartePar.historique = [];

    this.cartePar.historique.push(elementCarteHist);
    const crtHistoriqueRef = this.databaseRef.child('CarteParrainage').child(this.cartePar.uid.toString()).child('historique');
    crtHistoriqueRef.set(this.cartePar.historique);
  }

  getIdFilleul(filUid) {
    this.filleulExistList.forEach(fill => {
      fill.forEach(elementfillAf => {
        if (elementfillAf.uid === filUid) {
          this.filleulSelect = elementfillAf.familyname + ' '
            + elementfillAf.firstname;
          this.filleul = elementfillAf;
        }
      });
    });
  }

  getIdParrainCarte(parCartUid) {
    this.filleulExistList.forEach(parC => {
      parC.forEach(elementparC => {
        if (elementparC.uid === parCartUid) {
          this.ParrainCarteSelect = elementparC.familyname + ' '
            + elementparC.firstname;
          this.parrain = elementparC;
          for(let i = 0; i < this.filteredCartesTest.length; i++){
            if (this.filteredCartesTest[i].parrainCarte.uid === elementparC.uid) {
              this.cartePar = this.filteredCartesTest[i];
              if (this.cartePar.historique === undefined){
                this.cartePar.historique = new Array();
              }
              this.parrain = this.filteredCartesTest[i].parrainCarte;
            }else{
              console.log('Error');
            }
          }
        }
      });
    });
  }


  ngOnInit() {
    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(['/']);
    }
    this.subscription = this.opComService.getParrains()
      .subscribe(parrains => this.filleulTest = parrains);

  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
    this.subscriptionCarte.unsubscribe();
    this.radioFilleul = '';
    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.filleul = {
      uid: '',
      email: '',
      familyname: '',
      firstname: '',
      sex: '',
      birthday: new Date(),
      idCard: '',
      status: ''
    };

    this.scan = {
      uid: '',
      carteParrainID: '',
      carteFilleulID: '',
      dateCreation: new Date(),
      valeurParrain: '',
      valeurFilleul: '',
      type: '',
      operationCommercial: new OperationCommerciale()
    };
  }
}
