import { Component, OnInit, Output, EventEmitter, Input, SimpleChanges } from '@angular/core';
import { FormGroup, FormControl, Validators, ValidatorFn, AbstractControl } from '@angular/forms';
import { LocalStorageService, CustomerService } from '../../../../modules/shared/services';
import { runInThisContext } from 'vm';

@Component({
  selector: 'sts-dailog-create-customer',
  templateUrl: './dailog-create-customer.component.html',
  styleUrls: ['./dailog-create-customer.component.scss']
})
export class DailogCreateCustomerComponent implements OnInit {
  @Output() public createCustomer: EventEmitter<any> = new EventEmitter();
  @Output() public ignoreCustomerForm: EventEmitter<any> = new EventEmitter();
  @Output() public showCustomerCreateSpinner: EventEmitter<any> = new EventEmitter();
  @Output() public redirectToCustomerView: EventEmitter<any> = new EventEmitter();
  @Input() customerLabels;
  
  unsavedCustomerForm: Boolean = false;
  showSpinner: Boolean = false;
  showMsg: Boolean = false;
  customerForm: FormGroup;
  customerDetailData;
  status = '';
  message = '';
  
  customerModel = {
    In_CustomerInfo: {
      DealerID: '',
      MD__c: '',
      Owner: '',
      Personal_UCID__c: '',
      RecordType: '',
      Dealer_GC_Code__c: "GC0011430",
      Dealer_GS_Code__c: "GS0014313",
      StouchUniqueId: '',
      Address_Type__c: '',
      District__c: '',
      Gender__c: '',
      General_Personal_Info_Mandatory__c: '',
      LastName: '',
      MBK_Data_Source__c: '',
      PersonBirthdate: '',
      PersonEmail: '',
      PersonHomePhone: '',
      PersonMailingAddress: '',
      PersonMailingAddressline2: '',
      PersonMailingCity: '',
      PersonMailingPostalCode: '',
      PersonMailingState: '',
      PersonMobilePhone: '',
      Person_Agree_Test_Driving_Optional__c: '',
      Person_Info_Custom_Service_Optional__c: '',
      Targeted_Advert_Info_Optional_STCCC__c: '',
      Work_Phone__c: '',
      Town: ''
    }
  }

  reqheaderdataCustomer;

  constructor(
    private localStorageService: LocalStorageService,
    private customerService: CustomerService
  ) { }

  ngOnInit() {
    this.customerForm = new FormGroup({
      dataSource: new FormControl('', Validators.required),
      email: new FormControl('', [Validators.required, this.patternValidator(/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/)]),
      lastName: new FormControl('', Validators.required),
      gender: new FormControl('male', Validators.required),
      countryCode: new FormControl('+61', Validators.required),
      cityCode: new FormControl('', Validators.required),
      areaCode: new FormControl('', Validators.required),
      number: new FormControl('', Validators.required),
      state: new FormControl('', Validators.required)
    });
    this.getCustomerDetailData();
    this.reqheaderdataCustomer = this.localStorageService.getLocalStorageData("appConfig").apiUrl;
  }

  ngOnChanges(changes: SimpleChanges) {
    if (changes.customerLabels) {
      this.customerLabels = changes.customerLabels.currentValue;
    }
  }

  patternValidator(regexp: RegExp): ValidatorFn {
    return (control: AbstractControl): { [key: string]: any } => {
      const value = control.value;
      if (value === '') {
        return null;
      }
      return !regexp.test(value) ? { 'patternInvalid': { regexp } } : null;
    };
  }

  validateAllFields(formGroup: FormGroup) {
    Object.keys(formGroup.controls).forEach(field => {
      const control = formGroup.get(field);
      if (control instanceof FormControl) {
        control.markAsTouched({ onlySelf: true });
      } else if (control instanceof FormGroup) {
        this.validateAllFields(control);
      }
    });
  }

  getCustomerDetailData() {
    this.customerDetailData = this.localStorageService.getLocalStorageData("customerData");
  }

  onCustomerCreateFormSubmit() {
    let obj = this.customerForm.value;
    this.validateAllFields(this.customerForm);
    this.customerModel.In_CustomerInfo.MBK_Data_Source__c = obj.dataSource;
    this.customerModel.In_CustomerInfo.PersonEmail = obj.email;
    this.customerModel.In_CustomerInfo.LastName = obj.lastName;
    this.customerModel.In_CustomerInfo.Gender__c = obj.gender;
    this.customerModel.In_CustomerInfo.PersonMobilePhone = obj.countryCode + obj.cityCode + obj.areaCode + obj.number;
    this.customerModel.In_CustomerInfo.PersonMailingState = obj.state;
    this.customerModel.In_CustomerInfo.Personal_UCID__c = '';

    if (this.customerForm.valid) {
      this.unsavedCustomerForm = false;
      this.showSpinner= true;
      const body = this.customerModel;
      this.customerService.postCustomer(body, this.reqheaderdataCustomer).subscribe(
        data => {
          this.showSpinner= false;
          this.redirectToCustomerSearch();
        },
        error => {
          this.status = 'error';
          this.message = 'Customer creation failed.';
        }
      );
    }
  }

  goBackToCustomerSearch() {
    if (this.customerForm.dirty) {
      this.unsavedCustomerForm = true;
    } else {
      this.ignoreChanges();
    }
  }

  cancelChanges() {
    this.unsavedCustomerForm = false;
  }

  ignoreChanges() {
    this.ignoreCustomerForm.emit(true);
  }

  redirectToCustomerSearch(){
    this.redirectToCustomerView.emit(true);
    this.ignoreChanges();
  }

}
