import { Component, OnInit} from '@angular/core';
import { Router,ActivatedRoute } from '@angular/router';
import { WebService } from '../../provider/web.service';
import { SubjectService } from '../../provider/subject.service';
import { DataserviceService } from '../../provider/dataservice.service';

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

export class AddressComponent implements OnInit {
  loader : boolean;
  prdtData : any = new Array();
  product_id : any;
  address_id : number;
  userAddress : any;
  loginDetails : any;

  constructor(private route         : ActivatedRoute,
              private router        : Router, 
              public webService     : WebService,
              public subjectService : SubjectService,
              public dataService    : DataserviceService) { 
    this.loader     = true;
    this.address_id = 0;
  }

  ngOnInit() {
    this.checkUserLogin();
    this.checkProductId();
    this.getUserAddress();
  }

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

  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','');
    }
  }

  getUserAddress(){
    if(!this.loginDetails || !this.loginDetails.customer_id){
      return false;
    }
    this.loader = true;
    this.webService.post_data('getUserAddress',{'user_id':this.loginDetails.customer_id}).subscribe(response => {
      if(response.status == 'success'){
        this.userAddress = response.data;
      }else{
        this.userAddress = false;
      }
      this.loader = false;
    })
  }

  editAddress(address_id){
    if(address_id == ''){
      return false;
    }
    this.goToPage('addaddress',{"address_id":address_id});
  }

  select_address(address_id){
    if(address_id === ''){
      return false;
    }
    this.address_id = address_id;
  }

  deliverProduct(){
    if(this.address_id > 0){
      this.prdtData.address_id =  this.address_id;
      this.webService.setLocalStorageItem('productDetails', JSON.stringify(this.prdtData));
      this.goToPage('summary','');
    }
  }
  
  goToPage(path,data=null){
    this.router.navigate([path],{queryParams:  data});
    document.body.scrollTop  =  document.documentElement.scrollTop  =  0;
  }

}
