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 { AngularFireAuth } from 'angularfire2/auth';
import { AuthService } from '../../../services/auth/auth.service';
import { OpCommercialService } from '../../../services/opCommercial/op-commercial.service';
import { Commercant } from '../../../../models/Commercant';


@Component({
  selector: 'app-op-commercial',
  templateUrl: './op-commercial.component.html',
  styleUrls: ['./op-commercial.component.scss'],
  providers: [AuthService, OpCommercialService]
})
export class OpCommercialComponent implements OnInit, OnDestroy {
  opComm: OperationCommerciale;
  user: Observable<firebase.User>;
  opCommData: FirebaseListObservable<any[]>;
  profileData: FirebaseListObservable<any[]>;
  commercant: Commercant;
  statutAffiche: string;
  constructor(public afAuth: AngularFireAuth, public afDb: AngularFireDatabase,
              private router: Router) {
    this.statutAffiche = 'Toutes';
    this.opComm = new OperationCommerciale();

    this.user = afAuth.authState;
    this.commercant = new Commercant();
    this.user.subscribe(
      (auth) => {
        if (auth) {

          this.opCommData = this.afDb.list('/OperationCommercial/', {
              query: {
                orderByChild: 'commercantOpCom/uid',
                equalTo: auth.uid.toString()
              }
            }
          ).map((array) => array.reverse()) as FirebaseListObservable<any[]>;

          this.profileData = this.afDb.list('/' + auth.displayName + '/', {
              query: {
                orderByChild: 'uid',
                equalTo: auth.uid.toString()
              }
            }
          );
          this.profileData.forEach(utilisateur => {
            utilisateur.forEach(element => {
              this.commercant = element;
            });
          });
        }
      }
    );
  }

  activeOP(afficheStatus: string){
    this.statutAffiche = afficheStatus;
  }

  goToCreaOpCom() {
    this.router.navigate(['/creationOpCommercial']);
  }

  goToEnCart(idOp) {
    this.router.navigate(['/EnvoyerCarte', idOp]);
  }
  goToScanCart(idOp) {
    this.router.navigate(['/scannerCarte', idOp]);
  }
  goToDebiterCart(idOp) {
    this.router.navigate(['/debiterCarte', idOp]);
  }

  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() {}



}
