import { ActivatedRoute, Params } from '@angular/router';
import { Component, OnInit } from '@angular/core';
import { AlertService, QuotesService, UserService } from '../_services/';
import { Quote } from '../_models/quote';
import * as _ from 'lodash';
import { FormGroup, Validators, FormControl } from '@angular/forms';
import { Router } from '@angular/router';
import * as UAParser from 'ua-parser-js';

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

	quoteId: number;
	quote: Quote;
	seller: any;
	sideGlass: any;
	rearGlass: any;
  	public responseForm: FormGroup;
	public loading = false;
    userAgent: string;
    unique: any;
    left: any;
    right: any;
    price: any = null;
    sendToCustomer: boolean = false;

	constructor(private quotesService: QuotesService, private userService: UserService, private route: ActivatedRoute, private alertService: AlertService, private router: Router) {}

  	ngOnInit() {
		this.quoteId = this.route.snapshot.params['id'];
		this.getQuote();
  	}

	getQuote(){
		this.quotesService.getById(this.quoteId).subscribe((quote: any) => {
			this.quote = quote;
			this.price = quote.price;
			this.userAgent =  this.quote.userAgent.replace(new RegExp("\\\\", "g"), "");
			this.getSeller();
			this.getParts();
			this.getUserAgent();
			this.createForm();
		});
	}

	getSeller(){
		this.userService.getById(this.quote.userId).subscribe((user: any) => {
			this.seller = user;
		});
	}

	getParts(){	
		if(this.quote.sideGlass){
			this.sideGlass = JSON.parse(this.quote.sideGlass);
			console.log(this.sideGlass);
			_.each(this.sideGlass, function(item){
				console.log('sideGlass', item);
				//item.price = null;
			});
		}

		if(this.quote.rearGlass){
			this.rearGlass = JSON.parse(this.quote.rearGlass);
			if (this.rearGlass.price) {
				if (this.rearGlass.price[0]) {
					this.unique = (parseInt(this.rearGlass.price[0]) || null);
				}
				if (this.rearGlass.price[1]) {
					this.left = (parseInt(this.rearGlass.price[1]) || null);
				}
				if (this.rearGlass.price[2]) {
					this.right = (parseInt(this.rearGlass.price[2]) || null);
				}
			}
		}
	}

	getUserAgent(){
		var parser = new UAParser();
		parser.setUA(this.userAgent);
    	var result = parser.getResult();
    	this.userAgent = result;
	}

	onSubmit(event: any){
		let auth = false;
		if(this.responseForm.valid){

			if (this.sendToCustomer) {
				auth = window.confirm('¿Desea cerrar la cotizacion y enviar al cliente?');
			}
			else {
				auth = true;
			}
			if(auth){ 
				this.loading = true;
				let data = {
		  			'notes':this.responseForm.value.notes,
		  			'id': this.quote.id,
		  			'windscreenPrice': null,
		  			'securityPrice': null,
		  			'sideGlass': null,
		  			'rearGlass': null,
		  			'price': null,
		  			'sendToCustomer': (this.sendToCustomer ? 1 : 0)
		  		};

				if(this.quote.sideGlass != ""){
					data.sideGlass = JSON.stringify(this.sideGlass);
				}

				if(this.quote.rearGlass != ""){
					this.rearGlass.price = [this.unique, this.left, this.right];
					data.rearGlass = JSON.stringify(this.rearGlass);
				}

				if(this.quote.windscreenWiper){
		  			data.windscreenPrice = this.responseForm.value.windscreenPrice;
				}

				if(this.quote.securityFilm){
					data.securityPrice = this.responseForm.value.securityPrice; 
				}
	 
				if(this.price != null){
					data.price = this.price;
				}

				this.quotesService.updateQuote(data).subscribe((quote: any) => {
					if(quote.status == true && quote.sended == true){
						this.alertService.success('Cotización enviada a '+quote.email, true);
	          			this.router.navigateByUrl('/admin/seller/quotes');
					}
					else if(quote.status == true){
						this.alertService.success('Cotización guardada', true);
	          			this.router.navigateByUrl('/admin/seller/quotes');
					}
					else if (quote.status == false) {
						this.alertService.error(quote.msg, true);
	          			this.router.navigateByUrl('/admin/seller/quotes');
					}
				});
			}
			else {
				this.loading = false;
			}
      	} else {
			this.loading = false;
		}
	}

	unlist(id: any){
        let data = {'id':id};

		this.quotesService.unlistQuote(data).subscribe((quote: any) => {
			this.alertService.success('Cotización oculta', true);
      		this.router.navigateByUrl('/admin/seller/quotes');
		});
	}

	createForm() {
		if(this.quote.windscreenWiper == 1 && this.quote.securityFilm != 1){
	    	this.responseForm = new FormGroup({
	      		windscreenPrice: new FormControl(this.quote.windscreenPrice, {
	        		validators: Validators.required,
	        		updateOn: 'blur'
	      		}),
			  	notes: new FormControl(this.quote.notes, {
			    	validators: Validators.required,
			    	updateOn: 'blur'
			  	})
			});
		}

		else if (this.quote.securityFilm == 1 && this.quote.windscreenWiper != 1){
	    	this.responseForm = new FormGroup({
	      		securityPrice: new FormControl(this.quote.securityPrice, {
	        		validators: Validators.required,
	        		updateOn: 'blur'
	      		}),
			  	notes: new FormControl(this.quote.notes, {
			    	validators: Validators.required,
			    	updateOn: 'blur'
			  	})
			});
		}
		else if (this.quote.securityFilm == 1 && this.quote.windscreenWiper == 1) {
	    	this.responseForm = new FormGroup({
	      		windscreenPrice: new FormControl(this.quote.windscreenPrice, {
	        		validators: Validators.required,
	        		updateOn: 'blur'
	      		}),
	      		securityPrice: new FormControl(this.quote.securityPrice, {
	        		validators: Validators.required,
	        		updateOn: 'blur'
	      		}),
				notes: new FormControl(this.quote.notes, {
				  validators: Validators.required,
				  updateOn: 'blur'
				})
		  });	
		}
		else {
	    	this.responseForm = new FormGroup({
				notes: new FormControl(this.quote.notes, {
				  validators: Validators.required,
				  updateOn: 'blur'
				})
		  });
		}
		/*
		if(this.quote.windscreenWiper && this.quote.securityFilm){
	    	this.responseForm = new FormGroup({
	      		windscreenPrice: new FormControl(this.quote.windscreenPrice, {
	        		validators: Validators.required,
	        		updateOn: 'blur'
	      		}),
	      		securityPrice: new FormControl(this.quote.securityPrice, {
	        		validators: Validators.required,
	        		updateOn: 'blur'
	      		}),
			  	notes: new FormControl(this.quote.notes, {
			    	validators: Validators.required,
			    	updateOn: 'blur'
			  	})
			});
		}

		if(!this.quote.windscreenWiper && !this.quote.securityFilm){
	    	this.responseForm = new FormGroup({
			  	notes: new FormControl('', {
			    	validators: Validators.required,
			    	updateOn: 'blur'
			  	})
			});
		}
		*/
	}
}