import { Component, ViewChild, Injector, ElementRef, Output, EventEmitter } from '@angular/core';
import { ModalDirective } from 'ngx-bootstrap';
import { AppConsts } from '@shared/AppConsts';
import {
    AddressServiceProxy, ContactServiceProxy, UpdateContactInput, UpdateAddressInput,
     PostalCodeServiceProxy,
     PasswordComplexitySetting,UserEditDto,UserRoleDto,
     CreateOrUpdateUserInput, AddressTypeServiceProxy,
     ProfileServiceProxy,UserServiceProxy,
} from '@shared/service-proxies/service-proxies';
import * as _ from 'lodash';
import { AppComponentBase } from '@shared/common/app-component-base';

import { finalize } from 'rxjs/operators';
@Component({
  selector: 'editContactModal',
  templateUrl: './edit-contact-modal.component.html'
})
export class EditContactModalComponent extends AppComponentBase {

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


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

  contact: UpdateContactInput = new UpdateContactInput();
  user: UserEditDto = new UserEditDto();
  address: UpdateAddressInput = new UpdateAddressInput();
  country: any;
  filteredCountries: any;
  city: any;
  filteredCities: any;
  state: any;
  filteredStates: any;
  postal: any;
  filteredPostal: any;
  addressType: any;
  filteredAddressType: any;

  active: boolean = false;
  saving: boolean = false;

    canChangeUserName = 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();
    sendActivationEmail = true;
    setRandomPassword = false;
    passwordComplexityInfo = '';
    isActive: boolean;
    roles: UserRoleDto[];
    organizations: any[];

  constructor(
    injector: Injector,
    private _contactService: ContactServiceProxy,
    private _addressService: AddressServiceProxy,
    private _postalCodeService: PostalCodeServiceProxy,
    private _userService: UserServiceProxy,
    private _addressTypeService: AddressTypeServiceProxy,
    private _profileService: ProfileServiceProxy

  ) {
    super(injector);
  }
  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>';
}

  show(contactId: any, 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();
      });
  });

    this._contactService.getContact(
      contactId,undefined,undefined,undefined,undefined,undefined,undefined,undefined     
        ).subscribe((result)=> {
          console.log(result);
        this.country = result.items[0]['address']['country'];
        this.state = result.items[0]['address']['state'];
        this.city = result.items[0]['address']['city'];
        this.postal = result.items[0]['address']['postalCode'];
        this.addressType = result.items[0]['address']['addressType'];

        //contact input
        this.contact.id = contactId;
        this.contact.firstName = result.items[0]['user']['name'];
        this.contact.lastName = result.items[0]['user']['surname'];
        this.contact.userId = result.items[0]['user']['id'];
        this.contact.addressId = result.items[0]['address']['id'];

        //user input
        this.user.name = result.items[0]['user']['name'];
        this.user.surname = result.items[0]['user']['surname'];
        this.user.emailAddress = result.items[0]['user']['emailAddress'];
        this.user.phoneNumber = result.items[0]['user']['phoneNumber'];
        this.user.userName = result.items[0]['user']['userName'];
        this.user.id = result.items[0]['user']['id'];
        this.user.isActive = result.items[0]['user']['isActive'];

        //address input
        this.address.addressLine1 = result.items[0]['address']['addressLine1'];
        this.address.addressLine2 = result.items[0]['address']['addressLine2'];
        this.address.postalCodeId = this.postal['id'];
        this.address.addressTypeId = this.addressType['id'];
        //this.address.addressTypeId=== undefined ? this.address.addressTypeId= null : this.address.addressTypeId = this.addressType['id'];
        this.address.id = result.items[0]['address']['id'];
      this.modal.show();
      console.log(this.contact.firstName);
    });

  }

  save(): void {
    //this.addressType === null ?  this.address.addressTypeId = null : this.address.addressTypeId = this.addressType.id;
    
    let input = new CreateOrUpdateUserInput();
    input.user = this.user;
    input.setRandomPassword = this.setRandomPassword;
    input.sendActivationEmail = this.sendActivationEmail;
    input.assignedRoleNames = 
    _.map(
        _.filter(this.roles, { isAssigned: true }), role => role.roleName
    );
    input.organizationUnits = this.organizations;
    this.address.addressTypeId = this.addressType.id;
    this.contact.addressId = this.address.id;
    this.address.postalCodeId = this.postal.id;
    this.contact.userId = this.user.id;
    this.saving = true;
    
    this._contactService.updateContact(
        this.contact
    ).pipe(finalize(() => { this.saving = false; }))
    .subscribe(result => 
      {
        this._userService.createOrUpdateUser(input).subscribe(result => {
        });
        this._addressService.updateAddress(this.address).subscribe(result => {
        });
       
        this.notify.info(this.l('SavedSuccessfully'));
        this.close();
        this.modalSave.emit(null);
        console.log(this.user);
        console.log(this.address);
        console.log(this.contact);
    });
}
  
getAssignedRoleCount(): number {
  return _.filter(this.roles, { isAssigned: true }).length;
}

  onShown(): void {
   // this.nameInput.nativeElement.focus();
  }

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

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

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

}
