import { Component, Injector, ViewChild, ViewEncapsulation, Output, EventEmitter } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { appModuleAnimation } from '@shared/animations/routerTransition';
import { AppConsts } from '@shared/AppConsts';
import { AppComponentBase } from '@shared/common/app-component-base';
import {  CreateOrUpdateContactUserInput,VendorsServiceProxy, UserServiceProxy,
    LocationServiceProxy, CreateLocationContactInput, CreateContactInput,
    CreateAddressInput, PostalCodeServiceProxy, 
    CreateContactAddressInput,PasswordComplexitySetting,UserRoleDto,
    CreateContactUserAddressInput, UpdateContactInput, CreateEmailInput, CreatePhoneInput,
    ContactServiceProxy, UpdateAddressInput, ProfileServiceProxy, AddressServiceProxy,
    UserEditDto, EmailServiceProxy, PhoneServiceProxy,
    AddressTypeServiceProxy} from '@shared/service-proxies/service-proxies';
import { RoleListDto, RoleServiceProxy } 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 { ContactFormMainComponent } from '../../formMain/contact.form.component';
import { AddressFormMainComponent } from '../../formMain/address-form.component';
import { ModalDirective } from 'ngx-bootstrap';
declare var KTWizard: any
declare var ktwizard: any;
declare var $: any;

@Component({

    selector:'flyOutContactsModalComponent',
    templateUrl: './contacts-modal.component.html',
    encapsulation: ViewEncapsulation.None,
    animations: [appModuleAnimation()]

})

export class FlyOutContactsModalComponent extends AppComponentBase{

    @ViewChild(ContactFormMainComponent, {static:false}) contactForm;
    @ViewChild(AddressFormMainComponent, {static:false}) addressForm;
    @ViewChild('modalCreate', { static: true }) modal:ModalDirective

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

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

    user: UserEditDto = new UserEditDto();
    contact: CreateContactUserAddressInput = new CreateContactUserAddressInput();
    address: CreateAddressInput = new CreateAddressInput();
    contactInput: CreateContactInput = new CreateContactInput();
    createPhone: CreatePhoneInput = new CreatePhoneInput();
    createEmail : CreateEmailInput = new CreateEmailInput(); 

    
    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;

    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: any;
    sendActivationEmail = false;
    setRandomPassword = false;
    passwordComplexityInfo = '';


    _entityTypeFullName = 'SprintTek.Authorization.Roles.Role';
    entityHistoryEnabled = false;

    //Filters
    selectedPermission = '';

    constructor(

        injector:Injector,
        private _contactService: ContactServiceProxy,

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

        private _addressTypeService: AddressTypeServiceProxy,
        private _postalCodeService: PostalCodeServiceProxy,
        private _vendorService: VendorsServiceProxy,
        private router: Router,
        private route: ActivatedRoute,
        private _roleService: RoleServiceProxy,
        private _userService: UserServiceProxy,
        private _profileService: ProfileServiceProxy,
        private _addressService: AddressServiceProxy,
        private _emailService: EmailServiceProxy,
        private _phoneService: PhoneServiceProxy

    ){

        super(injector)
        $(document).ready(() => {
            //ktwizard('kt_wizard_v2', this.options);
             this.KTWizard2();
});

    }

   
    iconChanger(change: boolean){
        this.iconChange.emit(change)
    }


    show(): void{

        this.active=true
        this.modal.show()

    }

    close(): void{

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

    }


    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(){

        $('#UserName2').val('');
        $('.kt-select2').select2();
        this.route.paramMap.subscribe(params => {
            this.id = params.get("id")
        })
        ktwizard();
        $("#addressTypeSelectInput").change(function(){
            this.selectedAddressType = $("#addressTypeSelectInput option:selected").text();
            $("#selectedAddressType").text(this.selectedAddressType);
        });

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

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

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

    ngAfterViewInit() {
        let maxCount = 1000;
        
        this.getRoles();
        this.address = this.addressForm.address;

        this.user.name = this.contactForm.fName;
        this.user.surname = this.contactForm.sName;
        this.user.phoneNumber = this.contactForm.pNumber;
        this.user.emailAddress = this.contactForm.emailAddress;

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

    
    getAssignedRoleCount(): number {
        return _.filter(this.roles, { isAssigned: true }).length;
    }

    save(): void {
        console.log(this.contactForm);
        this.user.name = this.contactForm.fName;
        this.user.surname = this.contactForm.sName;
        this.user.phoneNumber = this.contactForm.pNumber;
        this.user.emailAddress = this.contactForm.emailAddress;
        let input = new CreateOrUpdateContactUserInput();


        this.address.postalCodeId = Number((<HTMLInputElement>document.getElementById('postalSelectInput')).value);
        
        if(Number((<HTMLInputElement>document.getElementById('addressTypeSelectInput')).value) == 0) {
            this.address.addressTypeId = null;
            
        }
        else {
            this.address.addressTypeId = Number((<HTMLInputElement>document.getElementById('addressTypeSelectInput')).value);
            
        }
        
        if(!$('#UserName2').val()){
             this._addressService.createAddress(this.address)
               .pipe(finalize(() => this.saving = false))
               .subscribe(addressResult => {
                       this.contactInput.firstName = this.user.name;
                       this.contactInput.lastName = this.user.surname;
                       this.contactInput.addressId = addressResult;
                           
                           this._contactService.createContact(this.contactInput)
                           .pipe(finalize(() => this.saving = false))
                           .subscribe(contactResult => {
                                   
                                   this.createPhone.contactId = contactResult;
                                   this.createEmail.contactId = contactResult;
                                   this.createPhone.value = this.user.phoneNumber;
                                   this.createEmail.value = this.user.emailAddress;

                                   this._phoneService.createPhone(this.createPhone)
                                         .pipe(finalize(() => this.saving = false))
                                         .subscribe(() => {

                                             this._emailService.createEmail(this.createEmail)
                                                   .pipe(finalize(() => this.saving = false))
                                                   .subscribe(() => {
                                                                this.notify.info(this.l("SavedSuccessfully"))
                                                                this.close()
                                                                this.iconChanger(true)
                                             });
                                   });    

                               
                           
                           });
             });

        } else{
                
                input.user = this.user;
                this.contact.firstName = input.user.name;
                this.contact.lastName = input.user.surname;
                input.setRandomPassword = this.setRandomPassword;
                input.user.isActive = this.isActive;
                input.sendActivationEmail = this.sendActivationEmail;
                input.assignedRoleNames = 
                _.map(
                    _.filter(this.roles, { isAssigned: true }), role => role.roleName
                );
                this.contact.contactUser = input;
                this.contact.address = this.address;
                this.saving = true;
                this._contactService.createContactUserAddress(this.contact)
                .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,
    //         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;
    //     });
    //   }   


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

      getRoles(userId?: number): void {
          this.active = true;
          
          this._userService.getUserForEdit(userId).subscribe(userResult => {
              this.user = userResult.user;
              this.roles = userResult.roles;
              this.canChangeUserName = this.user.userName !== AppConsts.userManagement.defaultAdminUserName;

              if (userId) {
                  this.active = true;

                  setTimeout(() => {
                      this.setRandomPassword = false;
                  }, 0);

                  this.sendActivationEmail = false;
              }

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

      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_v4', {
                startStep: 1,
            });

            // Change event
            wizard.on('change', function(wizard) {
                KTUtil.scrollTop();    
            });
        }

        wizardEl = KTUtil.get('kt_wizard_v4');
        formEl = $('#kt_form3').serialize();
        
        return initWizard();
        //return initValidation();
        //return initSubmit();
    }
}