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 { 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-debiter-carte',
  templateUrl: './debiter-carte.component.html',
  styleUrls: ['./debiter-carte.component.scss'],
  providers: [AuthService, OpCommercialService]
})
export class DebiterCarteComponent implements OnInit, OnDestroy {
  radioParrain: string;
  ParrainCarteSelect: string;
  user: Observable<firebase.User>;
  localUser: any;
  parrain: Parrain;
  commercant: Commercant;
  opComm: OperationCommerciale;
  cartePar: CarteParrainage;
  devise: string;

  opCommList: FirebaseListObservable<any[]>;
  parrainAffList: FirebaseListObservable<any[]>;
  filleulExistList: FirebaseListObservable<any[]>;
  databaseRef: any;


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


  carteTest: CarteParrainage[];
  codeTemp: string;
  valeurRecup: string;
  filteredCartesTest: any[];
  subscriptionCarte: Subscription;

  constructor(public afAuth: AngularFireAuth, public afDb: AngularFireDatabase,
              private router: Router, private opComService: OpCommercialService,
              private route: ActivatedRoute, private toastrService: ToastrService) {
    this.radioParrain = '';
    this.ParrainCarteSelect = '';
    this.localUser = new User();
    this.parrain = new Parrain();
    this.commercant = new Commercant();
    this.cartePar = new CarteParrainage();
    this.filleulExistList = null;
    this.parrainAffList = null;
    this.user = afAuth.authState;
    this.devise = 'euro';

    this.databaseRef = firebase.database().ref();
    this.user.subscribe(
      (auth) => {
        if (auth) {
          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.subscriptionCarte = this.opComService.getCartesOP(this.opComm.uid)
                  .subscribe(cartes => this.carteTest = cartes);
              });
            });
          });
          this.filleulExistList = this.afDb.list('/Parrain/', {
              query: {
                orderByChild: 'uid'
              }
            }
          );
        }
      });
  }
  filterCarte(query: string) {
    this.filteredCartesTest = (query) ?
      this.carteTest.filter(c => (c.parrainCarte.firstname.toLowerCase() + c.parrainCarte.familyname.toLowerCase())
        .includes(query.toLowerCase())) :
      [];
  }
  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 === this.parrain.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');
            }
          }
        }
      });
    });
  }
  debiterCarte() {

    this.cartePar.avantageCumule = ((+this.cartePar.avantageCumule) - (+this.valeurRecup)).toString();
    this.cartePar.avantageRecuperer = ((+this.cartePar.avantageRecuperer) + (+this.valeurRecup)).toString();


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

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

    //Historique carte

    var dateTemp = new Date (Date.now());
    var elementCarteHist = 'Le ' + dateTemp.getDate() + '/' + dateTemp.getMonth() + '/' + dateTemp.getFullYear()
      + ' à ' + dateTemp.getHours() + ':' + dateTemp.getMinutes()
      + ', ' + this.valeurRecup + '€ ont été récupérés sur cette carte par '
      + this.cartePar.parrainCarte.familyname.toUpperCase() + ' ' + this.cartePar.parrainCarte.firstname.toUpperCase() + '.';

    this.cartePar.historique.push(elementCarteHist);
    const crtHistoriqueRef = this.databaseRef.child('CarteParrainage').child(this.cartePar.uid.toString()).child('historique');
    crtHistoriqueRef.set(this.cartePar.historique);
    this.goToOpComm();
    this.toastrService.success('Débit de la carte de : ' + this.cartePar.parrainCarte.familyname + ' '
      + this.cartePar.parrainCarte.firstname);

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

  goToOpComm() {
    this.router.navigate(['/opCommercial']);
  }

  initdevise(devise: string) {
    this.devise = devise;
  }
  //////
  ngOnInit() {
    this.subscription = this.opComService.getParrains()
      .subscribe(parrains => this.parrainsTest = parrains);

    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(['/']);
    }
  }
//////

  ngOnDestroy() {
    this.subscription.unsubscribe();
    this.subscriptionCarte.unsubscribe();
    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: ''
    };
  }

}
