import { Component, Injector, ViewChild, ViewEncapsulation, ElementRef, 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 {  CreateOrUpdateContactUserInput,DriversServiceProxy,
    LocationServiceProxy, CreateLocationInput,UpdateLocationInput,
    UserLocationServiceProxy, CreateUserLocationInput,UpdateUserLocationInput,
    PasswordComplexitySetting,UserRoleDto,UserEditDto,
    CreateContactUserAddressInput,CreateAddressInput,
    CreateContactInput,CreatePhoneInput,CreateEmailInput,
    ContactServiceProxy, AddressTypeServiceProxy, PostalCodeServiceProxy,
    EmailServiceProxy,PhoneServiceProxy, ProfileServiceProxy, AddressServiceProxy} from '@shared/service-proxies/service-proxies';
import { LazyLoadEvent } from 'primeng/components/common/lazyloadevent';
import { finalize } from 'rxjs/operators';
import * as moment from 'moment';
import * as _ from 'lodash';
import { ContactFormComponent } from '@app/shared/layout/form/contact.form.component';
import { AddressFormComponent } from '@app/shared/layout/form/address-form.component';
import { ModalDirective } from 'ngx-bootstrap';
declare var ktwizard: any;
declare var KTWizard: any;
declare var $: any;

'use strict';

@Component({
    selector: 'flyOutDriverModalComponent',
    templateUrl: './driver-modal.component.html',
    encapsulation: ViewEncapsulation.None,
    animations: [appModuleAnimation()],
    styleUrls: ['driver-modal.component.less']

})
export class FlyOutDriverModalComponent extends AppComponentBase {

    @ViewChild('modalCreate', { static: true }) modal: ModalDirective
    @ViewChild('driverInput', { static: true }) driverInput: ElementRef

    @Output()iconChange = new EventEmitter<boolean>()


    active = false;
    saving = false;
    id: any;

    driver: UserEditDto = new UserEditDto();
    contact: CreateContactUserAddressInput = new CreateContactUserAddressInput();
    address: CreateAddressInput = new CreateAddressInput();
    contactInput: CreateContactInput = new CreateContactInput();

    
    defaultLocation: any;
    selectedLocation: any;
    location: any;
    filteredLocations: any;

    defaultAddressType: any;
    defaultCountry: any;
    defaultState: any;
    defaultPostal: any;
    defaultCity: any;

    selectedAddressType: any;
    selectedCountry: any;
    selectedPostalCode: any;
    selectedState: any;
    selectedCity: any;

    country: any;
    filteredCountries: any;
    city: any;
    filteredCities: any;
    state: any;
    filteredStates: any;
    postal: any;
    filteredPostal: any;
    addressType: any;
    filteredAddressType: any;
    filteredChange=false;

    canChangeUserName = true;
    isActive = true;
    isTwoFactorEnabled: boolean = false //this.setting.getBoolean('Abp.Zero.UserManagement.TwoFactorLogin.IsEnabled');
    isLockoutEnabled: boolean = false //this.setting.getBoolean('Abp.Zero.UserManagement.UserLockOut.IsEnabled');
    passwordComplexitySetting: PasswordComplexitySetting = new PasswordComplexitySetting();
    roles: UserRoleDto[];
    sendActivationEmail = false;
    setRandomPassword = false;
    passwordComplexityInfo = '';

    addressCheckBox = false;
    requiredState = true;
    
     
     options = {
        startStep: 1,
        manualStepForward: false
    };
wizard = new KTWizard('kt_wizard2',this.options);
    constructor(
        injector: Injector,
        private _locationService: LocationServiceProxy,
        private _driverService: DriversServiceProxy,
        private _userLocationService: UserLocationServiceProxy,
        private _contactService: ContactServiceProxy,

        // private _countryService: CountryServiceProxy,
        // private _cityService: CityServiceProxy,
        // private _stateService: StateServiceProxy,

        private _addressTypeService: AddressTypeServiceProxy,
        private _postalCodeService: PostalCodeServiceProxy,
        private _profileService: ProfileServiceProxy,
        private _addressService: AddressServiceProxy,
        private _emailService: EmailServiceProxy,
        private _phoneService: PhoneServiceProxy,
        private router: Router,
        private route: ActivatedRoute
    ) {
        super(injector);
        $(document).ready(() => {
            //ktwizard('kt_wizard_v2', this.options);
            this.KTWizard2();
});
        
    }

    setPasswordComplexityInfo(): void {

        this.passwordComplexityInfo = '<ul>';

        if (this.passwordComplexitySetting.requireDigit) {
            this.passwordComplexityInfo += '<li>' + this.l('PasswordComplexity_RequireDigit_Hint') + '</li>';
        }

        if (this.passwordComplexitySetting.requireLowercase) {
            this.passwordComplexityInfo += '<li>' + this.l('PasswordComplexity_RequireLowercase_Hint') + '</li>';
        }

        if (this.passwordComplexitySetting.requireUppercase) {
            this.passwordComplexityInfo += '<li>' + this.l('PasswordComplexity_RequireUppercase_Hint') + '</li>';
        }

        if (this.passwordComplexitySetting.requireNonAlphanumeric) {
            this.passwordComplexityInfo += '<li>' + this.l('PasswordComplexity_RequireNonAlphanumeric_Hint') + '</li>';
        }

        if (this.passwordComplexitySetting.requiredLength) {
            this.passwordComplexityInfo += '<li>' + this.l('PasswordComplexity_RequiredLength_Hint', this.passwordComplexitySetting.requiredLength) + '</li>';
        }

        this.passwordComplexityInfo += '</ul>';
    }

    
    ngOnInit(){
       var that=this;
        $('.kt-select2').select2();
        this.route.paramMap.subscribe(params => {
            this.id = params.get("id")
        })
        // $('#addressCheckbox').prop('checked', false);
        // $('#address').fadeOut('slow');

        $('#locationSelectInput').change(function(){
            this.selectedLocation = $("#locationSelectInput option:selected").text();
            $("#selectedLocation2").text(this.selectedLocation);
        })

        $("#citySelectInput2").change(function(){
            this.selectedCity = $("#citySelectInput2 option:selected").text();
            $("#selectedCity2").text(this.selectedCity);
        });

        $("#postalSelectInput2").change(function(){
            this.selectedPostalCode = $("#postalSelectInput2 option:selected").text();
            $("#selectedPostalCode2").text(this.selectedPostalCode);
            that.filteredChange=true;
            that.filterCountries(this.selectedPostalCode)
             console.log(this.selectedPostalCode);

            // that.filterStates(this.selectedPostalCode);
            // that.filterCities(this.selectedPostalCode);
        });

        $("#stateSelectInput2").change(function(){
            this.selectedState = $("#stateSelectInput2 option:selected").text();
            $("#selectedState2").text(this.selectedState);
        });

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

        $("#addressTypeSelectInputDriver").change(function(){
            this.selectedAddressType = $("#addressTypeSelectInputDriver option:selected").text();
            $("#selectedAddressType2").text(this.selectedAddressType);
        });

    }

    ngAfterViewInit(userId?: number) {
        
        var that=this;
        $('#addressCheckbox').change(function(){
            if(!this.checked)
                $('#address').fadeOut('slow');
            else
                $('#address').fadeIn('slow');
    
        });

        this._driverService.getDriverForEdit(userId).subscribe(res => {
            this.driver = res.user;

            this._profileService.getPasswordComplexitySetting().subscribe(passwordComplexityResult => {
                this.passwordComplexitySetting = passwordComplexityResult.setting;
                this.setPasswordComplexityInfo();
            });
        });

        
        
       
    }

    save(): void {
        this.saving = true;
       
        let userInput = new CreateOrUpdateContactUserInput({
           user : new UserEditDto({
               id: this.driver.id,
                name: this.driver.name,
                surname: this.driver.surname,
                userName: this.driver.userName,
                password: this.driver.password,
                phoneNumber: this.driver.phoneNumber,
                emailAddress: this.driver.emailAddress,
                isLockoutEnabled: false,
                isActive: this.isActive,
                isTwoFactorEnabled: this.isTwoFactorEnabled,
                shouldChangePasswordOnNextLogin: false      
            }),
            assignedRoleNames :  _.map(
                _.filter(this.roles, { isAssigned: true }), role => role.roleName
            ),
             sendActivationEmail : this.sendActivationEmail,
             setRandomPassword : this.setRandomPassword,
             location :  $("#locationSelectInput").val()
        });
      //  this._driverService.createOrUpdateDriver(userInput)
                if(!$('#address1').val() ){
                    
                    this.requiredState = false
                    this._driverService.createOrUpdateDriver(userInput)
                    .pipe(finalize(()=> {
                        this.saving = false;
                       
                     }))
                     .subscribe(() => {
                        this.notify.info(this.l('SavedSuccessfully'));
                        this.close()
                        this.iconChanger(true)
                         });
                }
                else{
                    this._driverService.createOrUpdateDriver(userInput)
                    .subscribe(
                        success=> {
                            console.log(success);
                            this.requiredState;
                            this.address.postalCodeId = Number((<HTMLInputElement>document.getElementById('postalSelectInput2')).value);
                            
                            if(Number((<HTMLInputElement>document.getElementById('addressTypeSelectInputDriver')).value) == 0) {
                                this.address.addressTypeId = null;
                                
                            }
                            else {
                                this.address.addressTypeId = Number((<HTMLInputElement>document.getElementById('addressTypeSelectInputDriver')).value);                   
                            }
                         
                            this._addressService.createAddress(this.address)
                            .subscribe(
                                addressResult=>{
                                    console.log(addressResult);
                                    this.contactInput.addressId = addressResult;
                                    this.contactInput.firstName = this.driver.name;
                                    this.contactInput.lastName = this.driver.surname;
                                    this.contactInput.userId = success;
                                console.log(this.contactInput);
                                this._contactService.createContact(this.contactInput)
                                .pipe(finalize(()=> {
                                    this.saving = false;
                                   
                                 }))
                                 .subscribe(() => {
                                    this.notify.info(this.l('SavedSuccessfully'));
                                    this.iconChanger(true)
                                    this.close()
                                     });
                                    
                    
                            });
                        },

                        error=> {
                            this.saving = false;
                        }
                    )
                    }
            }

            iconChanger(change: boolean){

                this.iconChange.emit(change)

            }

            KTWizard2(): void  {
                // Base elements
                var wizardEl;
                var formEl;
                var validator;
                var wizard;
                  
                // Private functions
                var initWizard = function () {
                    // Initialize form wizard
                    wizard = new KTWizard('kt_wizard2', {
                        startStep: 1,
                    });
        
                    // Validation before going to next page
        
                   
                    // Change event
                    wizard.on('change', function(wizard) {
                        KTUtil.scrollTop();    
                    });
                }
        
                wizardEl = KTUtil.get('kt_wizard2');
                formEl = $('#kt_form').serialize();
                
                return initWizard();
                //return initValidation();
                //return initSubmit();
            }

    filterLocations(maxcount): void {
        this._locationService.getLocation(
            undefined,
            undefined,
            undefined,
            maxcount,
            undefined
        ).subscribe(result => {
            this.filteredLocations = 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
                  console.log(result);
              })
    }

        filterStates(postalCodes: any): void {
        this._postalCodeService.getDistinctState(
            postalCodes,
            undefined
        ).subscribe(result => {
            this.filteredStates = result.items;
        });
      }   
  
      filterCities(postalCodes: any): void {
        this._postalCodeService.getDistinctCity(
            postalCodes,
            undefined
        ).subscribe(result => {
            this.filteredCities = result.items;
        });
      }
  
    


      filterAddressTypes(maxCount): void {
        this._addressTypeService.getAddressType(
            undefined,
            undefined,
            undefined,
            maxCount,
            undefined
        ).subscribe(result => {
            this.filteredAddressType = result.items;
        });
      }   

   

    show(): void{
        let maxcount = 1000;
        this.filterLocations(maxcount);
        // this.filterPostal(maxcount);
        // this.filterCountries(maxcount);
        // this.filterCities(maxcount);
        // this.filterStates(maxcount);
        this.filterAddressTypes(maxcount);
        this.filterPostal();
        this.active=true
        this.modal.show()

    }

    onShow(): void{



    }

    close(): void{

        this.active=false
        this.modal.hide()

    }




}