import { Component, Injector, ViewChild, ViewEncapsulation, ɵConsole } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { AppConsts } from '@shared/AppConsts';
import { appModuleAnimation } from '@shared/animations/routerTransition';
import { AppComponentBase } from '@shared/common/app-component-base';

import { AddressServiceProxy, ContactServiceProxy, UpdateContactInput, UpdateAddressInput, UpdatePhoneInput, UpdateEmailInput,

    PostalCodeServiceProxy, UserServiceProxy, ProfileServiceProxy,
    PasswordComplexitySetting,UserEditDto,UserRoleDto, EmailServiceProxy, PhoneServiceProxy,
    CreateOrUpdateUserInput, AddressTypeServiceProxy} 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';
declare var KTWizard: any;
declare var $: any;
declare var KTApp: any;

@Component({
    templateUrl: './edit-contact.component.html',
    encapsulation: ViewEncapsulation.None,
    animations: [appModuleAnimation()]
})
export class EditContactComponent extends AppComponentBase {

    @ViewChild(ContactFormComponent, {static:false}) contactForm;
    
    active = false;
    saving = false;
    id: any;
    organizations: any[];

    contact: UpdateContactInput = new UpdateContactInput();
    user: UserEditDto = new UserEditDto();
    address: UpdateAddressInput = new UpdateAddressInput();
    email: UpdateEmailInput = new UpdateEmailInput();
    phoneNumber: UpdatePhoneInput = new UpdatePhoneInput();
    
    defaultAddressType: any;
    defaultCountry: any;
    defaultState: any;
    defaultPostal: any;
    defaultCity: any;

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

    selected: 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: UserRoleDto[];
    sendActivationEmail = false;
    setRandomPassword = false;
    passwordComplexityInfo = '';
    isUser = true;
    detachRole = '';
    detachRoles = '';
    
    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 _addressService: AddressServiceProxy,
        private router: Router,
        private route: ActivatedRoute,
        private _profileService: ProfileServiceProxy,
        private _emailService: EmailServiceProxy,
        private _phoneService: PhoneServiceProxy
    ) {
        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>';
    }

    
    ngOnInit(){
        //this.detachRole = $('#role').detach();
        this.detachRoles = $('#roles').detach();
        
        this._profileService.getPasswordComplexitySetting().subscribe(passwordComplexityResult => {
            this.passwordComplexitySetting = passwordComplexityResult.setting;
            this.setPasswordComplexityInfo();
            
        });
    
        $('.kt-select2').select2();
        this.route.paramMap.subscribe(params => {
            this.id = params.get("id")
        })

        this._contactService.getContact(
            this.id,undefined,undefined,undefined,undefined,undefined,
            undefined,undefined
        ).subscribe((result) => {

            this.address.addressLine1 = result.items[0]['address']['addressLine1'];
            this.address.addressLine2 = result.items[0]['address']['addressLine2'];
            this.address.id = result.items[0]['address']['id'];
            this.address.addressTypeId = result.items[0]['address']['addressType']  === undefined? 0 : result.items[0]['address']['addressType']['id'];

            this.address.postalCodeId = result.items[0]['address']['postalCode']['id'];
            this.selectedCountry = result.items[0]['address']['postalCode']['country'];
            this.selectedPostalCode = result.items[0]['address']['postalCode']['value'];
            this.selectedState = result.items[0]['address']['postalCode']['state'];
            this.selectedCity = result.items[0]['address']['postalCode']['city'];
            this.selectedAddressType = result.items[0]['address']['addressType'] === undefined ? '' : this.selectedAddressType= result.items[0]['address']['addressType']['name'];

            if(result.items[0]['user']  === undefined) {
                this.contact.id = result.items[0]['id'];
                this.isUser = false;
                this.user.name = result.items[0]['firstName'];
                this.user.surname = result.items[0]['lastName'];
                $( "#user" ).hide();  
                this._emailService.getEmailList(
                    undefined,this.contact.id,undefined,undefined,undefined,undefined
                ).subscribe((resultEmail) => {
                    console.log(resultEmail.items);
                    this.user.emailAddress = resultEmail.items[0]['value'];
                    this.email.id = resultEmail.items[0]['id'];
                });
                this._phoneService.getPhone(
                    undefined,this.contact.id,undefined,undefined,undefined,undefined,undefined
                ).subscribe((resultPhone) => {
                    console.log(resultPhone.items);
                    this.user.phoneNumber = resultPhone.items[0]['value'];
                    this.phoneNumber.id = resultPhone.items[0]['id'];
                });
            }
            else {
                    this.isUser = true;
                    this.contact.userId = result.items[0]['user']['id'];
                    this.contact.addressId = result.items[0]['address']['id'];
                    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.password = result.items[0]['user']['password'];
                    this.getRoles(this.contact.userId);  
            }               
        });

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

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

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

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

    ngAfterViewInit() {
        this.KTWizard2();
    }

    save(): void {
        let input = new CreateOrUpdateUserInput();
            
        this.user.name = this.contactForm.fName;
        this.user.surname = this.contactForm.sName;
        if (this.contactForm.pNumber == null) {
            this.user.phoneNumber = "";
        } else {
            this.user.phoneNumber = this.contactForm.pNumber;
        }
        this.user.emailAddress = this.contactForm.emailAddress;
        this.contact.firstName = this.user.name;
        this.contact.lastName = this.user.surname;
        this.contact.id = this.id;
        //this.address.addressTypeId = Number((<HTMLInputElement>document.getElementById('addressTypeSelectInput')).value);
        if(Number((<HTMLInputElement>document.getElementById('addressTypeSelectInput')).value) == 0) {
            this.address.addressTypeId = null;
            
        }
        else {
            this.address.addressTypeId = Number((<HTMLInputElement>document.getElementById('addressTypeSelectInput')).value);
            
        }
        this.address.postalCodeId = Number((<HTMLInputElement>document.getElementById('postalSelectInput')).value);

        this.contact.addressId = this.address.id;

        if(this.isUser == false) {
                  this.email.contactId = this.contact.id;
                  this.phoneNumber.contactId = this.contact.id; 
                  this.email.value = this.user.emailAddress;
                  this.phoneNumber.value = this.user.phoneNumber;
                  this._contactService.updateContact(
                      this.contact
                  ).pipe(finalize(() => { this.saving = false; }))
                  .subscribe(resultContact => {
                      //this.contact.addressId = resultAddress;
                      this._addressService.updateAddress(
                          this.address
                      ).pipe(finalize(() => { this.saving = false; }))
                      .subscribe(resultAddress => {
                          
                              this._emailService.updateEmail(
                                  this.email
                              ).pipe(finalize(() => { this.saving = false; }))
                              .subscribe(result => {
                                      
                                      this._phoneService.updatePhone(
                                          this.phoneNumber
                                      ).pipe(finalize(() => { this.saving = false; }))
                                      .subscribe(result => {
                                          this.notify.info(this.l('SavedSuccessfully'));
                                          this.router.navigate(['/app/sprintship/contacts']);
                                      });    
                              });
                      });
                  
                  });
        }
        else {
            this.saving = true;
            console.log(this.id);
            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;
            input.user.isActive = this.isActive;
            this.contact.userId = this.user.id;
            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.router.navigate(['/app/sprintship/contacts']);
                        
                    });
                });
                
            });
        }
    }

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

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

            function validateEmail(sEmail) {
                var filter =/^\b[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b$/i;
                if (filter.test(sEmail)) {
                return true;
                }
                else {
                return false;
                }
            }
            // Validation before going to next page
            wizard.on('beforeNext', function (wizardObj) {
                if (wizardObj.currentStep == 1) {
                    if ($('#Name').val() == ''
                        || ($('#Surname').val() == '')
                        // || ($('#PhoneNumber').val() == ''||  $('#minutesPerStopInput').val()==0) 
                        || $('#EmailAddress').val() == ''
                        // || $('#UserName').val() == ''
                        // || $('#Password').val() == ''
                        // || $('#PasswordRepeat').val() == ''
                        // || $('.clsRoles:checkbox:checked').length == 0
                    ) {
                        wizardObj.stop();  // don't go to the next step
                    }
                    if(!validateEmail($('#EmailAddress').val())){
                        wizardObj.stop(); 
                    }
                    // if($("#roles").hasClass( "clsRoles" )){
                    //     if ($('.clsRoles:checkbox:checked').length == 0){
                    //         wizardObj.stop(); 
                    //     }
                    // }
                } else if (wizardObj.currentStep == 2) {
                    if ($('#address1Input').val() == ''
                        || ($('#countrySelectInput').val() == null || $('#countrySelectInput').val() == 0)
                        || ($('#postalSelectInput').val() == null || $('#postalSelectInput').val() == 0)
                        || ($('#stateSelectInput').val() == null || $('#stateSelectInput').val() == 0)
                        || ($('#citySelectInput').val() == null || $('#citySelectInput').val() == 0)
                        // || ($('#addressTypeSelectInput').val() == null || $('#addressTypeSelectInput').val() == 0)
                    ) {
                        wizardObj.stop();  // don't go to the next step
                    }
                }
            });
            // 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();
    }
}
