import { Component, EventEmitter, Injector, Output, ViewChild } from '@angular/core';
import { AppComponentBase } from '@shared/common/app-component-base';
import { AppConsts } from '@shared/AppConsts';
import {
    CreateOrUpdateContactUserInput,UserServiceProxy,
    LocationServiceProxy, CreateLocationContactInput, CreateContactInput,
    CreateAddressInput, PostalCodeServiceProxy, 
    CreateContactAddressInput,PasswordComplexitySetting,UserRoleDto,
    CreateContactUserAddressInput,
    ContactServiceProxy,ProfileServiceProxy,
    UserEditDto,
    AddressTypeServiceProxy

} from '@shared/service-proxies/service-proxies';
import * as _ from 'lodash';
import { ModalDirective } from 'ngx-bootstrap';
import { finalize } from 'rxjs/operators';

@Component({
    selector: 'createContactModal',
    templateUrl: './create-contact-modal.component.html'
})
export class CreateContactModalComponent extends AppComponentBase {

   @ViewChild('createModal', {static: false}) modal: ModalDirective;

    @Output() modalSave: EventEmitter<any> = new EventEmitter<any>();

    active = false;
    saving = false;
    user: UserEditDto = new UserEditDto();
    contact: CreateContactUserAddressInput = new CreateContactUserAddressInput();
    address: CreateAddressInput = new CreateAddressInput();
    country: any;
    filteredCountries: any;
    city: any;
    filteredCities: any;
    state: any;
    filteredStates: any;
    addressType: any;
    filteredAddressType: any;
    postal: any;
    filteredPostal: 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: UserRoleDto[];
    sendActivationEmail = false;
    setRandomPassword = false;
    passwordComplexityInfo = '';

    constructor(
        injector: Injector,
        private _contactService: ContactServiceProxy,
        // private _countryService: CountryServiceProxy,
        // private _cityService: CityServiceProxy,
        // private _stateService: StateServiceProxy,

        private _addressTypeService: AddressTypeServiceProxy,
        private _postalCodeService: PostalCodeServiceProxy,
        private _userService: UserServiceProxy,
        private _profileService: ProfileServiceProxy
    ) {
        super(injector);
    }

    show(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();
                this.modal.show();
            });
        });
    }

    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>';
    }


    onShown(): void {
       // document.getElementById('nameInput').focus();
        this.country = null;
        this.city = null;
        this.state = null;
        this.addressType = null;
        this.postal = null;
        this.user = new UserEditDto();
        this.contact = new CreateContactUserAddressInput();
        this.address = new CreateAddressInput();

    }

    init(): void {
      // this.location.contact = null;
    }

    save(): void {
       // this.addressType === null ?  this.address.addressTypeId = null : this.address.addressTypeId = this.addressType.id;
        let input = new CreateOrUpdateContactUserInput();
        input.user = this.user;
        this.address.addressTypeId = this.addressType.id;
        this.address.postalCodeId = this.postal.id;
        this.contact.address = this.address;
        input.setRandomPassword = this.setRandomPassword;
        input.sendActivationEmail = this.sendActivationEmail;
        input.assignedRoleNames = 
        _.map(
            _.filter(this.roles, { isAssigned: true }), role => role.roleName
        );
        this.contact.firstName = input.user.name;
        this.contact.lastName = input.user.surname;
        this.contact.contactUser = input;    
        this.saving = true;
        this._contactService.createContactUserAddress(this.contact)
            .pipe(finalize(() => { this.saving = false; }))
            .subscribe(() => {
                this.notify.info(this.l('SavedSuccessfully'));
                this.close();
                this.modalSave.emit(null);
            });
    }

    close(): void {
        this.active = false;
        this.modal.hide();
    }

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

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


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

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

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


    filterAddressType(event): void {
      this._addressTypeService.getAddressType(
          undefined,
          event.query,
          undefined,
          undefined,
          undefined
      ).subscribe(result => {
          this.filteredAddressType = result.items;
      });
    }

    
}
