import { Component, Injector, ViewChild, ViewEncapsulation, Output, EventEmitter } 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';
import { ModalDirective } from 'ngx-bootstrap';
declare var KTWizard: any;
declare var $: any;
declare var KTApp: any;

'use strict';

@Component({

    selector:'flyOutLocationModalComponent',
    templateUrl: './location-modal.component.html',
    encapsulation: ViewEncapsulation.None,
    animations: [appModuleAnimation()],
    styleUrls: ['location-modal.component.less']

})

export class FlyOutLocationModalComponent extends AppComponentBase{
    @ViewChild('modalCreate',{ static: true }) modal:ModalDirective
    @Output() iconChange = new EventEmitter<boolean>();
    
    
    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;
    filteredChange=false
    

    location: CreateLocationContactInput = new CreateLocationContactInput();
    contact: CreateContactAddressInput = new CreateContactAddressInput();
    address: CreateAddressInput = new CreateAddressInput();
    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 _countryService: CountryServiceProxy,
        // private _cityService: CityServiceProxy,
        // private _stateService: StateServiceProxy,

        private _timeZoneService: TimeZoneServiceProxy,
        private _postalCodeService: PostalCodeServiceProxy,
        private _addressService: AddressServiceProxy,
        private _contactService: ContactServiceProxy,
        private router: Router,
        private route: ActivatedRoute
    ) {
        super(injector);
        $(document).ready(() => {
                    //ktwizard('kt_wizard_v2', this.options);
                     this.KTWizard2();
        });
    }

    iconChanger(change:boolean){

        this.iconChange.emit(change)

    }



    ngOnInit(){
        var that=this;
        $('.kt-select2').select2();
        this.route.paramMap.subscribe(params => {
            this.id = params.get("id")
        })
        


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

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

        $("#postalSelectInputLocation").change(function(){
                this.selectedPostalCode = $("#postalSelectInputLocation option:selected").text();
                $("#selectedPostalCode").text(this.selectedPostalCode);
                // $('.kt-select2').select2();

                that.filteredChange = true;

                that.filterCountries(this.selectedPostalCode)
                that.filterStates(this.selectedPostalCode)
                that.filterCities(this.selectedPostalCode)
                
                // console.log("this")
        });

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

       
        
        
        
        
    }
    sample(): void{
        console.log("hello")
    }

    ngAfterViewInit(){
        let maxcount = 1000;
        this.filterTimeZones(maxcount);

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

        
    }

   
    save(): void {
        
        this.saving = true;
            this.address.postalCodeId = Number((<HTMLInputElement>document.getElementById('postalSelectInputLocation')).value);
            this.contact.address = this.address;
            this.location.timeZoneId = Number((<HTMLInputElement>document.getElementById('timeZoneSelectInput')).value);
            this.location.contact = this.contact;
            this._locationService.createLocationContact(this.location)
                .pipe(finalize(() => { this.saving = false; }))
                .subscribe(() => {
                    this.notify.info(this.l('SavedSuccessfully'));
                    this.close()
                    this.iconChanger(true)
                });
            
    }


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

      filterCountries(postalCode: any): void{
          this._postalCodeService
                .getDistinctCountry(
                    postalCode,
                    undefined
                ).subscribe(result =>{
                    this.filteredCountries = result.items
                })
        
      }

      filterStates(postalCode: any): void{
        this._postalCodeService
              .getDistinctState(
                  postalCode,
                  undefined
              ).subscribe(result =>{
                  this.filteredStates = result.items
              })
      
    }

    filterCities(postalCode: any): void{
        this._postalCodeService
              .getDistinctCity(
                  postalCode,
                  undefined
              ).subscribe(result =>{
                  this.filteredCities = 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;
      });
    }


    // Class definition
    KTWizard2(): 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,
            });

            // 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();
    }   

    show(): void{
        
        this.filterPostal();
        
        // this.filterCountries(maxcount)
        this.active=true
        this.modal.show();
        
    }
    
    close():void{
        this.filteredChange=false
        this.modal.hide();
        this.active=false
    }
}

