import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { NavBarService } from '../admin.service';
import { AuthService } from '../../services/auth.service';
import { FormBuilder, FormGroup, Validators, AbstractControl } from '@angular/forms';
import { ToastsManager } from 'ng2-toastr/ng2-toastr';
import { environment } from '../../../environments/environment.dev';

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

  img_path = environment.imageUrl+'/assets/img/admin/';
  prefs = [
    {name: 'INDIA'},
    {name: 'USA'}
   ];

   userForm: FormGroup;
  selectedFilter = 1;
  filters = [
    { name: 'Country', pWidth: 'auto' },
    { name: 'All', pWidth: '30px' }
  ];

  locations = [];
  dismiss = 'none';
  errMsg = '';
  tableData = {
    headers: ['Address', 'City', 'State / Provinces', 'Country'],
    rows: [],
    dialogData: { title: 'Location', text: 'Would you like to delete this location from the list?'}
  };

  constructor(
    private router: Router,
    private fb: FormBuilder,
    private navBarService: NavBarService,
    private AuthService: AuthService,
    private toastr: ToastsManager) {

    this.getAllLocation()

  }

  ngOnInit() {
    this.errMsg = ''
    this.navBarService.setCurrentPage(8);
    this.userForm = this.fb.group({
      address: ['', Validators.required],
      city: ['', Validators.required],
      state: ['', Validators.required],
      country: ['Select', Validators.required],
      zipCode: ['', Validators.required],

    });
  }
  onSubmit(value: string): void {
    console.log('you submitted value: ', value);


    this.errMsg = ''
    if (value['country'] == 'Select'){
      this.errMsg = "Please select country";
    }else if (value['state'] == '' || value['state'] == 'undefined' || value['state']== null ){
      this.errMsg = "Please enter valid state";
    }else if (value['city'] == '' || value['city'] == 'undefined' || value['city']== null ){
      this.errMsg = "Please enter valid city";
    }else if (value['address'] == '' || value['address'] == 'undefined' || value['address']== null ){
      this.errMsg = "Please enter valid address";
    }else if (value['zipCode'] == '' || value['zipCode'] == 'undefined' || value['zipCode']== null ){
      this.errMsg = "Please enter valid zipCode";
    }else {


      this.AuthService.getAddLocation(value).then(resp => {

        console.log(resp, 'Response for getAddLocation')

        if (resp.error == null) {

          this.dismiss = 'modal'

          this.getAllLocation()

          this.userForm = this.fb.group({
            address: ['', Validators.required],
            city: ['', Validators.required],
            state: ['', Validators.required],
            country: ['Select', Validators.required],
            zipCode: ['', Validators.required],

          });

          this.toastr.success('Location added successfully');

        }
        else {
          console.log(resp, 'Response for getAddLocation')

        }

      }).catch(err => {

        console.log(err, 'Error')

      })
    }
  }


  getAllLocation(){


    this.AuthService.getAllLocations().then(resp =>{

      console.log(resp,'getAllLocations')

      this.locations = resp.pgLocationList
      this.tableData.rows = this.locations.map(function (item, index, array) {
        return [item.address, item.city, item.state, item.country];
      });

    }).catch(err =>{

      console.log(err)
    })

  }

  edit(index) {
    console.log('Editing item: ', this.locations[index]);
    this.router.navigate(['/admin/location/' + this.locations[index].locationId]);
  }

  delete(index) {
    console.log('Deleting item: ', this.locations[index]);
    var location = this.locations[index] ;
    console.log(location)

    this.AuthService.getDeleteLocation(location.locationId).then(resp => {

      if (resp.status == 'error') {
        this.toastr.error(resp.message);
      } else {
        this.toastr.success(resp.successMessage);
        this.tableData.rows.splice(index, 1);
      }
    }).catch(err => {
      console.log(err)
    })
  }

}
