import { Component, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { BaseComponent } from '../base/base.component';
import { QuotesService } from '../_services';
import { AuthenticationService } from '../_services/authentication.service';
import { AlertService } from '../_services';
import { Quote } from '../_models';
import { Observable } from 'rxjs/Rx';
import * as UAParser from 'ua-parser-js';
import { $ } from 'protractor';
declare var jQuery: any;

@Component({
  selector: 'app-seller-quotes',
  templateUrl: './seller-quotes.component.html',
  styleUrls: ['./seller-quotes.component.css']
})
export class SellerQuotesComponent extends BaseComponent implements OnInit, OnDestroy {

	quotes: Quote;
  searchId: any = "";
  searchEmail: any = "";
  userAgent: any;
  

  /* pagination */
  public loading: any;
  public itemsPerPage = 5;
  public offset = 0;
  public paginator = false;
  public total = 0;
  public currentPage = 1;
  public sub: any;
  public status: string = "0";
  public searchFrom: string = "";
  public searchTo: string = "";

	constructor(
        private router: Router,
        private auth: AuthenticationService,
        private quotesService: QuotesService,
        private alertService: AlertService
	) {
		super();
    this.itemsPerPage = this.CONSTANTS.users.perPage;
    console.log('Create Subtimer');
    this.sub = Observable.interval(1000 * 60).subscribe(x => {
      let e = {'first':0};
      this.loadLazy(e);
    });

  }

  	ngOnInit() {
      //this.getPendingQuotes();
      jQuery("#dateDesde").datepicker();
      jQuery("#dateHasta").datepicker();
  	}

    ngOnDestroy(){
      console.log('Destroy Subtimer');
      this.sub.unsubscribe();
    }

  	getPendingQuotes(){
      const data = {
        perPage: 1,
        page: 1,
        email: this.searchEmail,
        id: this.searchId,
        status: this.status,
        searchTo: this.searchTo,
        searchFrom: this.searchFrom
      };
  		this.quotesService.getFilteredQuotes(data).subscribe((quotes: any) => {
    		this.quotes = quotes.data;
    	}, err => this.handleError(err));
  	}


    loadLazy(e: any) {
      let current = (e.first / this.CONSTANTS.users.perPage) + 1; 

      const data = {
          "id":this.searchId,
          "email":this.searchEmail,
          status: this.status,
          searchTo: this.searchTo,
          searchFrom: this.searchFrom,
          perPage: this.CONSTANTS.users.perPage,
          page: current
      };
      console.log(data);
      this.loading = true;
      this.quotesService.getFilteredQuotes(data).subscribe((quotes: any) => {
        this.loading = false;
        this.quotes = quotes.data;
        this.total = quotes.total;
        this.currentPage = quotes.current_page; 

        if (this.total > this.itemsPerPage) { 
            this.paginator = true; 
        }

      }, err => this.handleError(err));
    }

    updateData(){

      this.searchTo = jQuery("#dateHasta").val();
      this.searchFrom = jQuery("#dateDesde").val();
      this.currentPage = 1;
      const data = {
          "id":this.searchId,
          "email":this.searchEmail,
          status: this.status, 
          searchTo: this.searchTo,
          searchFrom: this.searchFrom,
          perPage: this.CONSTANTS.users.perPage,
          page: this.currentPage
      };

      this.quotesService.getFilteredQuotes(data).subscribe((quotes: any) => {
        /*console.log(quotes);*/
        this.alertService.clear();
        if(quotes.data.length == 0){
          this.alertService.error("No hay resultados para la busqueda.",false);
        }

        this.loading = false;
        this.quotes = quotes.data;
        this.total = quotes.total;
        this.currentPage = quotes.current_page; 

        if (this.total > this.itemsPerPage) { 
            this.paginator = true; 
        }

      }, err => this.handleError(err));
  }

  showUserAgent(quote: any){
    this.userAgent =  quote.userAgent.replace(new RegExp("\\\\", "g"), "");
    var parser = new UAParser();
    parser.setUA(this.userAgent);
    var result = parser.getResult();

    if(result.os.name=='Windows')
      return "Computador - Windows";

    if(result.os.name=='Linux')
      return "Computador - Linux";

    if(result.os.name=='Android')
      return "Teléfono - Android";

    if(result.os.name=='iPhone')
      return "Teléfono - iPhone";

    if(result.os.name=='RIM Tablet OS')
      return "Tablet";

    return "Dispositivo desconocido";
  }

  private handleError(error: any): Promise<any> {
    console.error(this.constructor.name + ': An error occurred', error);
      if (error.error.msg === this.CONSTANTS.servicesMsg.NOT_AUTHORIZED) {
          this.auth.logout();
          this.router.navigate(['/login']);
      }
      return Promise.reject(error.message || error);
  }
}
