import { Component, OnInit, OnDestroy, Input } 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 { ToastrService } from '../../../typescripts/angular-bootstrap-md/pro';

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 { FireImg } from '../../../../models/FireImg';
import {Commercant} from '../../../../models/Commercant';


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

  fileList: FirebaseListObservable<FireImg[]>;

  opComm: OperationCommerciale;


  user: Observable<firebase.User>;
  opCommData: FirebaseListObservable<any[]>;
  minDateTimeTest: Date;
  maxDateTimeTest: Date;
  debutDateTimeTest: Date;
  finDateTimeTest: Date;
  todayDateTimeTest: Date;
  devise: string;
  devise2: string;
  fileOpCom: boolean;

  dateDebutVal: boolean;
  dateFinVal: boolean;

  constructor(public afAuth: AngularFireAuth, public afDb: AngularFireDatabase,
              private router: Router, private opComService: OpCommercialService,
              private toastrService: ToastrService) {
    this.dateFinVal = false;
    this.dateDebutVal = false;
    this.opComm = new OperationCommerciale();
    this.devise = 'euro';
    this.devise2 = 'euro';
    this.fileOpCom = true;
    this.user = afAuth.authState;
    this.minDateTimeTest = new Date('1917-01-01');
    this.maxDateTimeTest = new Date('2117-01-01');
    this.debutDateTimeTest = new Date(this.opComm.dateDebut);
    this.finDateTimeTest = new Date(this.opComm.dateFin);
    this.todayDateTimeTest = new Date(Date.now());
  }

  fileOKOpCom() {
    this.fileOpCom = false;
  }
  creerOpComm() {
    this.user.subscribe(
      (auth) => {
        if (auth) {
          this.opCommData = this.afDb.list('/Commercant/', {
              query: {
                orderByChild: 'uid',
                equalTo: auth.uid.toString()
              }
            }
          );
          this.opCommData.forEach(utilisateur => {
            utilisateur.forEach(element => {
              this.opComm.commercantOpCom = element;
              this.opComm.status = 'Inactive';
              this.opComm.nbScan = '';
              this.opComm.nbEnvoie  = '';
              this.opComm.nbDebiter  = '';
              this.opComm.validationXJC = 'En Cours';
              this.opComService.saveOpComm(element, this.opComm);
              this.goToOpComm();
            });
          });
        }
      }
    );
    this.toastrService.success("Création d'une nouvelle opération commerciale: " + this.opComm.name);
  }
  validationDateDebut(){

    this.debutDateTimeTest = new Date(this.opComm.dateDebut);
    this.finDateTimeTest = new Date(this.opComm.dateFin);
    this.todayDateTimeTest = new Date(Date.now());
    this.todayDateTimeTest = new Date(this.todayDateTimeTest.getTime() - 100000000);
    if (this.debutDateTimeTest.getTime() <= (this.todayDateTimeTest.getTime())
      || this.debutDateTimeTest.getTime() >= this.maxDateTimeTest.getTime()) {

      this.dateDebutVal = true;
      return true;
    } else {
      return false;
    }
  }


  validationDateFin(){

    this.debutDateTimeTest = new Date(this.opComm.dateDebut);
    this.finDateTimeTest = new Date(this.opComm.dateFin);
    this.todayDateTimeTest = new Date(Date.now());
    if (this.finDateTimeTest.getTime() < this.debutDateTimeTest.getTime()
      || this.finDateTimeTest.getTime() >= this.maxDateTimeTest.getTime()) {
      this.dateFinVal = true;
      return true;
    } else {
      return false;
    }
  }

  initdevise(devise: string) {
    this.devise = devise;

  }

  initdevise2(devise: string) {
    this.devise2 = devise;
  }


  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(['/']);
    }
  }
  goToOpComm() {
    this.router.navigate(['/opCommercial']);
  }

  ngOnDestroy() {
    this.opComm = {
      uid : '',
      name : '',
      commercantOpCom : new Commercant(),
      dateDebut : new Date(),
      dateFin : new Date(),
      carteTemplate : new FireImg(),
      avantageParrain : '',
      deviseAvantageParrain : '',
      tarifXJCParrain : '',
      avantageFilleul : '',
      deviseAvantageFilleul : '',
      tarifXJCFilleul : '',
      status : '',
      nbScan : '',
      nbEnvoie  : '',
      nbDebiter  : '',
      validationXJC : ''
    };
  }
}
