import { Component, OnInit , HostListener } from '@angular/core';
import { Router,ActivatedRoute } from '@angular/router';
import { FormGroup, FormControl, FormBuilder, Validators, ValidationErrors } from '@angular/forms';
import { WebService } from '../../provider/web.service';
import { ValidationService } from '../../provider/validation.service';
import { SubjectService } from '../../provider/subject.service';

@Component({
  selector: 'app-addaddress',
  templateUrl: './addaddress.component.html',
  styleUrls: ['./addaddress.component.scss']
})

export class AddaddressComponent implements OnInit {
  loader              : boolean;
  address_id          : any;
  loginDetails        : any;
  editAddressResp     : any;
  addressResponse     : any;
  addressSubmitClick  : boolean;
  prdtData:any = new Array();
  product_id:any;
  
  addaddressForm: FormGroup;
  name = new FormControl('', [Validators.required]);
  city = new FormControl('', [Validators.required]);
  area = new FormControl('', [Validators.required]);
  state = new FormControl('', [Validators.required]);
  landmark = new FormControl('');
  house_no = new FormControl('', [Validators.required]);
  phone_no = new FormControl('', [Validators.required, Validators.pattern("^[0-9\ ( ) + , - ]+$")]);
  address_type = new FormControl('1');

  constructor(private router        : Router, 
              private route         : ActivatedRoute,
              public errorMsg       : ValidationService,
              public webService     : WebService,
              private formBuilder   : FormBuilder,
              public subjectService : SubjectService) { 
    this.loginDetails        = false;
    this.addressSubmitClick  = false;
  }

  ngOnInit() {
    this.route.params.subscribe(val => {
      this.route.queryParams.subscribe(params => {
        this.address_id = params['address_id'];
      });
    });
    this.checkUserLogin();
    this.checkProductId();
    this.buildAddressForm();

    if(this.address_id > 0){
      this.getUserAddressById(this.address_id);
    }
  }

  buildAddressForm(){
    this.addaddressForm = this.formBuilder.group({
      name: this.name,
      city: this.city,
      area: this.area,
      state: this.state,
      landmark: this.landmark,
      house_no: this.house_no,
      phone_no: this.phone_no,
      address_type: this.address_type
    });
  }

  checkProductId(){
    this.prdtData = JSON.parse(this.webService.getLocalStorageItem('productDetails'));
  
    if(this.prdtData && this.prdtData['product_id'] > 0){
      this.product_id = this.prdtData['product_id'];
    }else{
      this.goToPage('purchaseHome','');
    }
  }

  checkUserLogin(){
    this.loginDetails = JSON.parse(this.webService.getLocalStorageItem('userData'));
    if(!this.loginDetails){
      this.goToPage('purchaseHome','');
    }
    this.subjectService.getLoginData().subscribe(loginData => {
      this.loginDetails = JSON.parse(this.webService.getLocalStorageItem('userData'));
    });
  }

  addressFormSubmit(data){
    if(this.addaddressForm.invalid){
      return false;
    }
    if(this.address_id > 0){
      this.updateAddressFormSubmit(data,this.address_id);
    }else{
      this.addaddressFormSubmit(data)
    }
  }
  
  addaddressFormSubmit(data){
    this.loader = true;
    const This = this;
    data.customer_id = this.loginDetails.customer_id;
    this.webService.post_data('saveUserAddress',data).subscribe(response => {
      this.loader = false;
      if(response.status == 'success'){
        this.addressResponse = response;

        setTimeout( function() {
          This.addressResponse = false;
          This.goToPage('address','');
          This.addaddressForm.reset();
          This.addressResponse = false;
          This.addressSubmitClick = false;
        }, 3000);
      }else{
        response.message = (response.message == '')?this.errorMsg.errorList.req_failure:response.message;
        this.addressResponse = response;
        setTimeout( function() {
          This.addressResponse = false;
        }, 3000);
      }
    })
  }
  updateAddressFormSubmit(data,id){
    this.loader = true;
    const This = this;
    data.customer_id = this.loginDetails.customer_id;
    this.webService.post_data('updateUserAddress',{"data":data,"address_id":id}).subscribe(response => {
      this.loader = false;
      if(response.status == 'success'){
        this.addressResponse = response;

        setTimeout( function() {
          This.addressResponse = false;
          This.goToPage('address','');
          This.addaddressForm.reset();
          This.addressResponse = false;
          This.addressSubmitClick = false;
        }, 3000);
      }else{
        response.message = (response.message == '')?this.errorMsg.errorList.req_failure:response.message;
        this.addressResponse = response;
        setTimeout( function() {
          This.addressResponse = false;
        }, 3000);
      }
    })
  }

  getUserAddressById(address_id){
    this.loader = true;
    this.webService.post_data('getUserAddressById',{"address_id":address_id,'customer_id':this.loginDetails.customer_id}).subscribe(response => {
      this.loader = false;
      if(response.status == 'success'){
        this.editAddressResp = response.data;

        this.addaddressForm.controls["city"].setValue(this.editAddressResp.city);
        this.addaddressForm.controls["area"].setValue(this.editAddressResp.area);
        this.addaddressForm.controls["state"].setValue(this.editAddressResp.state);
        this.addaddressForm.controls["landmark"].setValue(this.editAddressResp.landmark);
        this.addaddressForm.controls["house_no"].setValue(this.editAddressResp.house_no);
        this.addaddressForm.controls["phone_no"].setValue(this.editAddressResp.phone_no);
        this.addaddressForm.controls["name"].setValue(this.editAddressResp.name);
        this.addaddressForm.controls["address_type"].setValue(this.editAddressResp.address_type);
      }
    })
  }

  goToPage(path,data=null){
    this.router.navigate([path],{queryParams:  data});
    document.body.scrollTop  =  document.documentElement.scrollTop  =  0;
  }
}
