import { Component, OnInit, OnDestroy } from '@angular/core';
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';

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

import * as firebase from 'firebase/app';
import * as _ from 'lodash';
import { AngularFireAuth } from 'angularfire2/auth';
import { AuthService } from '../../../services/auth/auth.service';
import { OpCommercialService } from '../../../services/opCommercial/op-commercial.service';
import { Commercant } from '../../../../models/Commercant';
import { Admin } from '../../../../models/Admin';

@Component({
  selector: 'app-liste-op-commercial',
  templateUrl: './liste-op-commercial.component.html',
  styleUrls: ['./liste-op-commercial.component.scss'],
  providers: [AuthService, OpCommercialService]
})
export class ListeOpCommercialComponent implements OnInit, OnDestroy  {
  opComm: OperationCommerciale;
  user: Observable<firebase.User>;
  opCommData: FirebaseListObservable<any[]>;
  opCommDataValider: OperationCommerciale[];
  opCommDataBloquer: FirebaseListObservable<any[]>;
  profileData: FirebaseListObservable<any[]>;
  adminData: FirebaseListObservable<any[]>;
  admin: Admin;
  commercant: Commercant;
  databaseRef: any;
  opCommercials: any;
  filteredOpCommercials: any;
  test: any;
  filters = {};
  avantageCumulerAdmin: string;
  constructor(public afAuth: AngularFireAuth, public afDb: AngularFireDatabase,
              private router: Router) {
    this.admin = new Admin();
    this.opComm = new OperationCommerciale();
    this.databaseRef = firebase.database().ref();
    this.opCommDataValider = [];
    this.user = afAuth.authState;
    this.commercant = new Commercant();
    this.user.subscribe(
      (auth) => {
        if (auth) {
          // Admin
          console.log('ououou admin: ' + auth.uid);
          this.adminData = this.afDb.list('/Admin/', {
              query: {
                orderByChild: 'uid',
                equalTo: auth.uid
              }
            }
          );
          this.adminData.forEach(avantage => {
            avantage.forEach(elementavantage => {
              console.log('elementavantage' + elementavantage.email);
              this.admin = elementavantage;
              console.log(this.admin.avantageCumule);
            });
          });


          this.opCommDataBloquer = this.afDb.list('/OperationCommercial/',{
            query: {
              orderByChild: 'status',
              equalTo: 'Bloqué'
            }
          });

          this.test = this.afDb.list('/OperationCommercial/',{
            query: {
              orderByChild: 'validationXJC',
              equalTo: 'Validé'
            }
          }).subscribe(opComs => {
            this.opCommercials = opComs;
            this.applyFilters(this.filteredOpCommercials, this.opCommercials);
            this.filterDifferentDe('status', 'Bloqué');
          });
        }
      }
    );
  }

  goToCarteEnvoyer(id: string) {
    this.router.navigate(['ListCarteEnvoyerAdmin', id]);
  }
  goToScanEffectuer(id: string) {
    this.router.navigate(['ListScanEffecterAdmin', id]);
  }
  applyFilters(listFiltrer: any, listAFiltrer: any) {
    this.filteredOpCommercials = _.filter(this.opCommercials, _.conforms(this.filters));
  }

  filterEgual(property: string, query: string) {
    this.filters[property] = val => val === query;
  }

  filterDifferentDe(property: string, query: string) {
    this.filters[property] = val => val !== query;
  }

  bloquer(uidRejeter: string) {
    const opEnvRef = this.databaseRef.child('OperationCommercial').child(uidRejeter).child('status');
    opEnvRef.set('Bloqué');
  }

  debloquer(opDebloquer: OperationCommerciale){

    var todayTemp = new Date(Date.now());
    var debutTemp = new Date(opDebloquer.dateDebut);
    var finTemp = new Date(opDebloquer.dateFin);

    if (todayTemp.getTime() >= debutTemp.getTime() && todayTemp.getTime() <= finTemp.getTime()) {
      opDebloquer.status = 'Active';
      opDebloquer.validationXJC = 'Validé';
    } else {
      opDebloquer.status = 'Inactive';
    }

    const opDebloquerRef = this.databaseRef.child('OperationCommercial').child(opDebloquer.uid.toString()).child('status');
    opDebloquerRef.set(opDebloquer.status);
  }

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

}
