import { Component, Injector, OnInit, ViewChild, ViewEncapsulation } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { appModuleAnimation } from '@shared/animations/routerTransition';
import { AppComponentBase } from '@shared/common/app-component-base';
import {
    LocationServiceProxy, CreateLocationContactInput, AddressServiceProxy, CreateContactInput, ContactServiceProxy, CreateAddressInput, UpdateLocationInput, UpdateContactInput, UpdateAddressInput, TimeZoneServiceProxy, PostalCodeServiceProxy, CreateContactAddressInput
} from '@shared/service-proxies/service-proxies';
import { LazyLoadEvent } from 'primeng/components/common/lazyloadevent';
import { Paginator } from 'primeng/components/paginator/paginator';
import { Table } from 'primeng/components/table/table';
import { finalize } from 'rxjs/operators';
import * as moment from 'moment';
import { PrimengTableHelper } from '@shared/helpers/PrimengTableHelper';
import * as _ from 'lodash';
declare var KTWizard: any;
declare var $: any;
declare var KTApp: any;

'use strict';

@Component({
    templateUrl: './edit-location.component.html',
    encapsulation: ViewEncapsulation.None,
    animations: [appModuleAnimation()]
})
export class EditLocationComponent extends AppComponentBase implements OnInit {

    // @ViewChild('dataTable', {static: true}) dataTable: Table;
    // @ViewChild('paginator', {static: true}) paginator: Paginator;
    // @ViewChild('createOrderModal') createOrderModal: CreateOrderModalComponent;
    options: {
        startStep: 1,
        manualStepForward: false
    };
    
    id: any;
    active = false;
    saving = false;

    

    defaultTimezone: any;
    defaultCountry: any;
    defaultState: any;
    defaultPostal: any;
    defaultCity: any;

    selectedTimezone: any;
    selectedCountry: any;
    selectedPostalCode: any;
    selectedState: any;
    selectedCity: any;

    location: UpdateLocationInput = new UpdateLocationInput();
    contact: UpdateContactInput = new UpdateContactInput();
    address: UpdateAddressInput = new UpdateAddressInput();
    country: any;
    filteredCountries: any;
    city: any;
    filteredCities: any;
    state: any;
    filteredStates: any;
    timeZone: any;
    filteredTimeZones: any;
    postal: any;
    filteredPostal: any;
    swal: any;
    validator: any;
    constructor(
        injector: Injector,
        private _locationService: LocationServiceProxy,
        private _timeZoneService: TimeZoneServiceProxy,
        private _postalCodeService: PostalCodeServiceProxy,
        private _addressService: AddressServiceProxy,
        private _contactService: ContactServiceProxy,
        private router: Router,
        private route: ActivatedRoute
    ) {
        super(injector);
        $(document).ready(() => {
                    this.default(this.id); 
                    this.ktwizard();
        });
    }

    
    
    ngOnInit(){
        
        this.route.paramMap.subscribe(params => {
            this.id = params.get("id")
        })
       
       $("#timeZoneSelectInput").change(function(){
               this.selectedTimezone = $("#timeZoneSelectInput option:selected").text();
               $("#selectedTimezone").text(this.selectedTimezone);
       });

       $("#countrySelectInput").change(function(){
               this.selectedCountry = $("#countrySelectInput option:selected").text();
               $("#selectedCountry").text(this.selectedCountry);
       });

       $("#postalSelectInput").change(function(){
               this.selectedPostalCode = $("#postalSelectInput option:selected").text();
               
               $("#selectedPostalCode").text(this.selectedPostalCode);
       });

       $("#stateSelectInput").change(function(){
               this.selectedState = $("#stateSelectInput option:selected").text();
               $("#selectedState").text(this.selectedState);
       });
       $("#citySelectInput").change(function(){
               this.selectedCity = $("#citySelectInput option:selected").text();
               $("#selectedCity").text(this.selectedCity);
       });
       
        
    }

    ngAfterViewInit(){

        $('.kt-select2').select2();
        
    }

   
    save(): void {
        this.saving = true;
        this.location.timeZoneId = Number((<HTMLInputElement>document.getElementById('timeZoneSelectInput')).value);
        this.address.postalCodeId = Number((<HTMLInputElement>document.getElementById('postalSelectInput')).value);
        this._locationService.updateLocation(
            this.location
        ).pipe(finalize(() => { this.saving = false; }))
        .subscribe(result => {
              this._addressService.updateAddress(this.address).subscribe(result => {
                this._contactService.updateContact(this.contact).subscribe(result => {
                    this.notify.info(this.l('SavedSuccessfully'));
                    this.router.navigate(['/app/sprintship/locations']);
                });
              });
        });
    }


    // filterPostal(maxcount): void {
    //   this._postalCodeService.getPostalCode(
    //       undefined,
    //       undefined,
    //       undefined,
    //       maxcount,
    //       undefined
    //   ).subscribe(result => {
    //       this.filteredPostal = result.items;
    //   });
    // }

    // filterCountries(maxcount): void {
    //   this._countryService.getCountry(
    //       undefined,
    //       undefined,
    //       undefined,
    //       maxcount,
    //       undefined
    //   ).subscribe(result => {
    //       this.filteredCountries = result.items;
    //   });
    // }

    // filterCities(maxcount): void {
    //   this._cityService.getCity(
    //       undefined,
    //       undefined,
    //       undefined,
    //       maxcount,
    //       undefined
    //   ).subscribe(result => {
    //       this.filteredCities = result.items;
    //   });
    // }

    // filterStates(maxcount): void {
    //   this._stateService.getState(
    //       undefined,
    //       undefined,
    //       undefined,
    //       maxcount,
    //       undefined
    //   ).subscribe(result => {
    //       this.filteredStates = result.items;
    //   });
    // }


    filterTimeZones(maxcount): void {
      this._timeZoneService.getTimeZone(
          undefined,
          undefined,
          undefined,
          maxcount,
          undefined
      ).subscribe(result => {
          this.filteredTimeZones = result.items;
          //$(".kt-content").show();
          
      });
    }

    default(locationId: any): void {
        this.active = true;
        //$(".kt-content").hide();
        let maxcount = 1000;
        this._locationService.getLocation(locationId, undefined, undefined, undefined, undefined)
            .subscribe(result => {
            // this.locations = result.items;
            if(result.items[0]['contact'] != undefined) {
                
              this.defaultCountry = result.items[0]['contact']['address']['country']['id'];
              this.defaultState = result.items[0]['contact']['address']['state']['id'];
              this.defaultCity = result.items[0]['contact']['address']['city']['id'];
              this.defaultPostal = result.items[0]['contact']['address']['postalCode']['id'];

              this.selectedCountry = result.items[0]['contact']['address']['country']['name'];
              this.selectedPostalCode = result.items[0]['contact']['address']['postalCode']['name'];
              this.selectedState = result.items[0]['contact']['address']['state']['name'];
              this.selectedCity = result.items[0]['contact']['address']['city']['name'];
              
              //contact input
              this.contact.firstName = result.items[0]['contact']['firstName'];
              this.contact.lastName = result.items[0]['contact']['lastName'];
              this.contact.addressId = result.items[0]['contact']['address']['id'];
              
              //address input
              this.address.addressLine1 = result.items[0]['contact']['address']['addressLine1'];
              this.address.addressLine2 = result.items[0]['contact']['address']['addressLine2'];
              //this.address.postalCodeId = this.postal['id'];
              this.address.id = result.items[0]['contact']['address']['id'];
              this.contact.id = result.items[0]['contactId'];
                  
            }

            this.defaultTimezone = result.items[0]['timeZoneId'];
            
            //location Input
            this.location.id = locationId;
            this.location.name = result.items[0]['name'];
            this.location.minutesPerMile = result.items[0]['minutesPerMile'];
            this.location.minutesPerStop = result.items[0]['minutesPerStop'];
            this.location.contactId = result.items[0]['contactId'];
            console.log(this.location.name);
            this.selectedTimezone = result.items[0]['timeZone']['value'];
            this.filterTimeZones(maxcount);

            // this.filterCountries(maxcount);
            // this.filterPostal(maxcount);
            // this.filterCities(maxcount);
            // this.filterStates(maxcount);

        });
    }

    
    navigate(url: any, id?: number){
        if(id != null){
            var myurl = `${url}/${id}`;
        }else{
            var myurl = `${url}`;
        }
        console.log(myurl);
        this.router.navigateByUrl(myurl);
    }
    
    // Class definition
     ktwizard(): void  {
        // Base elements
        var wizardEl;
        var formEl;
        var validator;
        var wizard;
          
        // Private functions
        var initWizard = function () {
            // Initialize form wizard
            wizard = new KTWizard('kt_wizard_v2', {
                startStep: 1,
            });

            // Validation before going to next page
            wizard.on('beforeNext', function(wizardObj) {
               if(wizardObj.currentStep == 1) {
                if($('#nameInput').val() == '' 
                || $('#minutesPerMileInput').val() == '' 
                || $('#minutesPerStopInput').val() == ''
                || $('#timeZoneSelectInput').val() == '') {
                  wizardObj.stop();  // don't go to the next step
                }
               }
               else if(wizardObj.currentStep == 2) {
                  if($('#firstNameInput').val() == '' || $('#lastNameInput').val() == '') {
                    wizardObj.stop();  // don't go to the next step
                  }
               }
               else if(wizardObj.currentStep == 3) {
                  if($('#address1Input').val() == '' || $('#countrySelectInput').val() == '' || $('#postalSelectInput').val() == '' || $('#stateSelectInput').val() == '' || $('#citySelectInput').val() == '') {
                        wizardObj.stop();
                  }
               }
            //    console.log(wizardObj.currentStep);
               //console.log($(#nameInput).val());
            });
            // Change event
            wizard.on('change', function(wizard) {
                KTUtil.scrollTop();    
            });
        }
        wizardEl = KTUtil.get('kt_wizard_v2');
        formEl = $('#kt_form').serialize();
        
        return initWizard();
        //return initValidation();
        //return initSubmit();
    }
}
