import { Injectable, Input } from '@angular/core';
import { Router } from '@angular/router';

import * as firebase from 'firebase/app';
import 'firebase/storage';
import { AngularFireAuth } from 'angularfire2/auth';
import { AngularFireDatabase, FirebaseListObservable } from 'angularfire2/database';

import { Parrain } from '../../../models/Parrain';
import { Commercant } from '../../../models/Commercant';
import { OperationCommerciale } from '../../../models/OperationCommerciale';
import { CarteParrainage } from '../../../models/CarteParrainage';

@Injectable()
export class OpCommercialService {
  databaseRef: any;
  storageRef: any;
  parrain: Parrain;
  commercant: Commercant;
  test: string;

  @Input() folder: string;

  constructor(public afAuth: AngularFireAuth, public afDb: AngularFireDatabase, public router: Router) {
    this.databaseRef = firebase.database().ref();
    this.storageRef = firebase.storage().ref();
  }

  getParrains(): FirebaseListObservable<any> {
    return this.afDb.list('/Parrain/', {
        query: {
          orderByChild: 'uid'
        }
      }
    );
  }

  getCommercants(): FirebaseListObservable<any> {
    return this.afDb.list('/Commercant/', {
        query: {
          orderByChild: 'commercialName'
        }
      }
    );
  }

  getOpComs(): FirebaseListObservable<any> {
    return this.afDb.list('/OperationCommercial/', {
        query: {
          orderByChild: 'uid'
        }
      }
    );
  }
  getCartes(): FirebaseListObservable<any> {
    return this.afDb.list('/CarteParrainage/', {
        query: {
          orderByChild: 'uid'
        }
      }
    );
  }
  getCartesOP(opCommUid): FirebaseListObservable<any> {
    return this.afDb.list('/CarteParrainage/', {
        query: {
          orderByChild: 'operationCommercialCarte/uid',
          equalTo: opCommUid
        }
      }
    );
  }

  getScansOP(opCommUid): FirebaseListObservable<any> {
    return this.afDb.list('/Scan/', {
        query: {
          orderByChild: 'operationCommercial/uid',
          equalTo: opCommUid
        }
      }
    );
  }

  updateNbCarteOpCom(opCommUid, nbCartesOpCom) {

    nbCartesOpCom.subscribe(tabNbCartesOpCom => {
      if (tabNbCartesOpCom.length > 0) {
        console.log('');
        // const upCartOpRef = firebase.database().ref().child('OperationCommercial').child('-KwlMJtE2d3WfrD5n94s').child('nbEnvoie');
        // upCartOpRef.set(tabNbCartesOpCom.length);
        // console.log('tabNbCartesOpCom.length: ' + tabNbCartesOpCom.length);
        // const upCartOpRef = firebase.database().ref().child('OperationCommercial').child(opCommUid).child('nbEnvoie');
        // upCartOpRef.set(tabNbCartesOpCom.length);
      }else{
        // console.log('tous mettre a 0');
        console.log('');
        // const upCartOpRef = firebase.database().ref().child('OperationCommercial').child('-KwlMJtE2d3WfrD5n94s').child('nbEnvoie');
        // upCartOpRef.set('');
        // const upCartOpRef = firebase.database().ref().child('OperationCommercial').child(opCommUid).child('nbEnvoie');
        // upCartOpRef.set('');
      }
    });
  }

  updateNbScanOpCom(opCommUid, scansOpCom) {

    scansOpCom.subscribe(tabScansOpCom => {
      if (tabScansOpCom.length > 0) {

        // const uptabcanOpComOpRef = firebase.database().ref().child('OperationCommercial').child(opCommUid).child('nbEnvoie');
        // upCartOpRef.set(tabCartesOpCom.length);
        for (let i = 0; i < tabScansOpCom.length; ++i) {
          //console.log('tabcansOpCom.length: ' + tabScansOpCom.length + ' ' + tabScansOpCom[i].name);
          console.log('');
        }
      }else{
        console.log('');
        // const upCartOpRef = firebase.database().ref().child('OperationCommercial').child(opCommUid).child('nbEnvoie');
        // upCartOpRef.set('');
      }
    });
  }

  updateOpCommEnvScanDebi(opComAll) {
    opComAll.subscribe(tabOpComs => {
      if (tabOpComs.length > 0) {
        for (let i = 0; i < tabOpComs.length; ++i) {
          if (tabOpComs[i].name !== '') {
            let monOpCom = tabOpComs[i];
            if (monOpCom !== undefined) {
              let nbCartesOpCom = this.getCartesOP(tabOpComs[i].uid);
              let scansOpCom = this.getScansOP(tabOpComs[i].uid);
              nbCartesOpCom.subscribe(tab => {
                const upCartOpRef = firebase.database().ref().child('OperationCommercial').child(tabOpComs[i].uid).child('nbEnvoie');
                let testEnv = (tab.length === 0 ? '' : tab.length.toString());
                upCartOpRef.set(testEnv);
              });
              scansOpCom.subscribe(tabS => {
                const upScanOpRef = firebase.database().ref().child('OperationCommercial').child(tabOpComs[i].uid).child('nbScan');
                let testScan = (tabS.length === 0 ? '' : tabS.length.toString());
                upScanOpRef.set(testScan);
              });
              // this.updateNbCarteOpCom(tabOpComs[i].uid, nbCartesOpCom);
              // this.updateNbScanOpCom(tabOpComs[i].uid, scansOpCom);
            }
          }
        }
      }
    });
  }

  updateOpCommStatus(opComAll) {

    opComAll.subscribe(tabOpComs => {
      if (tabOpComs.length > 0) {
        for (let i = 0; i < tabOpComs.length ; ++i){
          if (tabOpComs[i].name !== '') {
            let monOpCom = tabOpComs[i];

            if (monOpCom !== undefined){
              var todayTemp = new Date(Date.now());
              var debutTemp = new Date(monOpCom.dateDebut);
              var finTemp = new Date(monOpCom.dateFin);
              if (monOpCom.status !== 'Bloqué') {
                if (todayTemp.getTime() >= debutTemp.getTime() && todayTemp.getTime() <= finTemp.getTime()) {
                  if (monOpCom.uid !== undefined && monOpCom.status !== undefined && monOpCom.name !== undefined
                    && monOpCom.uid !== '' && monOpCom.status !== '' && monOpCom.name !== '') {
                    monOpCom.status = 'Active';
                  }
                } else {
                  if (monOpCom.uid !== undefined && monOpCom.status !== undefined && monOpCom.name !== undefined
                    && monOpCom.uid !== '' && monOpCom.status !== '' && monOpCom.name !== ''){
                    monOpCom.status = 'Inactive';
                  }
                }
                if (monOpCom.uid !== undefined && monOpCom.status !== undefined && monOpCom.name !== undefined
                  && monOpCom.uid !== '' && monOpCom.status !== '' && monOpCom.name !== '') {
                  const carteStatusRef = firebase.database().ref().child('OperationCommercial').child(monOpCom.uid).child('status');
                  carteStatusRef.set(monOpCom.status);
                }
              }
            }

          }
        }
      }
    });
  }

  updateCarteEtOpCom() {

    const opComAll = this.getOpComs();
    const carteAll = this.getCartes();
    this.updateOpCommStatus(opComAll);
    this.updateCarteStatus(carteAll);
    this.updateOpCommEnvScanDebi(opComAll);
  }


  updateCarteStatus(carteAll){
    carteAll.subscribe(tabCarte => {
        if (tabCarte.length > 0) {
          for (let i = 0; i < tabCarte.length ; ++i){
            if (tabCarte[i].parrainCarte.firstname !== '') {
              let maCarte = tabCarte[i];

              if(maCarte !== undefined) {
                var todayTemp = new Date(Date.now());
                var debutTemp = new Date(maCarte.dateDebut);
                var finTemp = new Date(maCarte.dateFin);
                if (todayTemp.getTime() >= debutTemp.getTime() && todayTemp.getTime() <= finTemp.getTime()) {
                  if(maCarte.status !== undefined && maCarte.uid !== undefined && maCarte.parrainCarte !== undefined
                    && maCarte.status !== '' && maCarte.uid !== '' && maCarte.parrainCarte.firstname !== '') {
                    maCarte.status = 'Active';
                  }
                } else {
                  if (maCarte.status !== undefined && maCarte.uid !== undefined && maCarte.parrainCarte !== undefined
                    && maCarte.status !== '' && maCarte.uid !== '' && maCarte.parrainCarte.firstname !== '') {
                    maCarte.status = 'Inactive';
                  }
                }
                if (maCarte.status !== undefined && maCarte.uid !== undefined && maCarte.parrainCarte !== undefined
                  && maCarte.status !== '' && maCarte.uid !== '' && maCarte.parrainCarte.firstname !== '') {
                  const carteStatusRef = firebase.database().ref().child('CarteParrainage').child(maCarte.uid).child('status');
                  carteStatusRef.set(maCarte.status);
                }

              }
            }
          }
        }
    });
  }

  saveOpComm(user: firebase.User, infoOpCom: OperationCommerciale) {
    if (infoOpCom.name !== '' && infoOpCom.avantageParrain !== '' && infoOpCom.avantageFilleul !== '') {
      infoOpCom.uid = firebase.database().ref().child('OperationCommercial').push().key;
      let updates = {};
      updates['/OperationCommercial/' + infoOpCom.uid] = infoOpCom;
      firebase.database().ref().update(updates);
      this.upload(infoOpCom);
    }

  }


  upload(info: any) {
    // Create a root reference
    let storageRef = firebase.storage().ref();
    this.folder = '/OperationCommercial/' + info.uid + '/carteTemplate';

    if ((<HTMLInputElement>document.getElementById('orangeForm-File')) !== null) {
      for (let selectedFile of [(<HTMLInputElement>document.getElementById('orangeForm-File')).files[0]]) {
        // Make local copies of services because "this" will be clobbered
        let router = this.router;

        let folder = this.folder;

        let path = `${this.folder}`;

        let iRef = storageRef.child(path);

        iRef.put(selectedFile).then((snapshot) => {
          let updates = {};
          info.carteTemplate.path = path;
          info.carteTemplate.filename = info.name;
          info.carteTemplate.downloadURL = snapshot.downloadURL;
          updates[folder] = info.carteTemplate;
          firebase.database().ref().update(updates);
        });
      }
    }
  }
}
