import { AfterViewChecked, ChangeDetectorRef, Component, ViewContainerRef } from '@angular/core';

import { ActivatedRoute, Router } from '@angular/router';
import { DynaDataService, AuditDialogService, ConfirmationDialogService, IFormView } from '@xdf/gallery';
import { TranslateService } from '@ngx-translate/core';
import { NotificationService, InitCommonsService, NotificationType } from '@xdf/commons';
import { NavigationService } from '@xdf/layouts';
import { FormGroup, FormControl, Validators, ValidationErrors } from '@angular/forms';
import { BusinessParametersService } from '../services/business-parameters.service';
import { ChangeHistoryDialogService } from './components/services/change-history-dialog.service';

@Component({
  selector: 'byte-business-parameters-form',
  templateUrl: './business-parameters-form.component.html',
  styleUrls: ['./business-parameters-form.component.scss']
})
export class BusinessParametersFormComponent extends IFormView implements AfterViewChecked {
  icon = '<i class=\"material-icons\">business_center</i>';
  disabledFields = ['id', 'key'];
  isRequiredValueActivated: boolean = false;
  message: string;
  flag: boolean = false;
  temp: string;

  constructor(
    protected vcRef: ViewContainerRef,
    protected route: ActivatedRoute,
    protected router: Router,
    protected dynaDataService: DynaDataService,
    protected translate: TranslateService,
    protected notificationService: NotificationService,
    protected auditDialogService: AuditDialogService,
    protected confirmationDialogService: ConfirmationDialogService,
    protected navigationService: NavigationService,
    protected init: InitCommonsService,
    protected businessParametersService: BusinessParametersService,
    protected dialogService: ChangeHistoryDialogService,
    private readonly changeDetectorRef: ChangeDetectorRef
  ) {
    super(vcRef, route, router, dynaDataService, translate, notificationService, auditDialogService, confirmationDialogService, init);
  }

  ngAfterViewChecked(): void {
    this.changeDetectorRef.detectChanges();
    if (this.mode === 'edit' || this.mode === 'new') {
      if (this.form && this.form.controls['required']) {
        this.form.controls['required'].enable();
      }
    }
  }

  protected getFields(): FormGroup {
    let form;
    if (this.mode !== 'new') {
      form = new FormGroup({
        id: new FormControl({ value: this.getValueFromRecord('id'), disabled: this.disabledCondition('id') }),
        key: new FormControl({ value: this.getValueFromRecord('key'), disabled: this.disabledCondition('key') }, [Validators.required]),
        description: new FormControl({ value: this.getValueFromRecord('description'), disabled: this.disabledCondition('description') }, [Validators.required]),
        required: new FormControl({ value: this.getValueFromRecord('required') === "Y", disabled: this.disabledCondition('required') }, [Validators.required]),
        currentValue: new FormControl({ value: this.getValueFromRecord('currentValue'), disabled: this.disabledCondition('currentValue') }),
        dateFrom: new FormControl({ value: this.getValueFromRecord('dateFrom'), disabled: this.disabledCondition('dateFrom') }),
      });
      if (this.record && this.record['required'] !== undefined) {
        if (this.record['required'] === 'Y') {
          form.addControl('defaultValue', new FormControl({ value: this.getValueFromRecord('defaultValue'), disabled: this.disabledCondition('defaultValue') }));
        }
      }
      if (this.record && this.record['currentValue'] !== undefined) {
        form.addControl('programmedValue', new FormControl({ value: this.getValueFromRecord('programmedValue'), disabled: this.disabledCondition('programmedValue') }));
        form.addControl('dateApplyFrom', new FormControl({ value: this.getValueFromRecord('dateApplyFrom'), disabled: this.disabledCondition('dateApplyFrom') }));
      }
    } else {
      this.isRequiredValueActivated = false;
      form = new FormGroup({
        id: new FormControl({ value: '', disabled: this.disabledCondition('id') }),
        key: new FormControl({ value: '', disabled: this.disabledCondition('key') }, [Validators.required]),
        description: new FormControl({ value: '', disabled: this.disabledCondition('description') }, [Validators.required]),
        required: new FormControl({ value: '', disabled: this.disabledCondition('required') }),
        currentValue: new FormControl({ value: '', disabled: this.disabledCondition('currentValue') }),
        dateFrom: new FormControl({ value: '', disabled: this.disabledCondition('dateFrom') }),
      });
      if (this.record && this.record['required'] !== undefined) {
        if (this.record['required'] === 'Y') {
          form.addControl('defaultValue', new FormControl({ value: this.getValueFromRecord('defaultValue'), disabled: this.disabledCondition('defaultValue') }));
        }
      }
      if (this.record && this.record['currentValue'] !== undefined) {
        form.addControl('programmedValue', new FormControl({ value: this.getValueFromRecord('programmedValue'), disabled: this.disabledCondition('programmedValue') }));
        form.addControl('dateApplyFrom', new FormControl({ value: this.getValueFromRecord('dateApplyFrom'), disabled: this.disabledCondition('dateApplyFrom') }));
      }
    }
    return form;
  }

  getValueFromRecord(name: string) {
    let value = '';
    if (this.record && this.record[name]) {
      value = this.record[name];
    }
    return value;
  }

  openModal() {
    this.dialogService.loadComponent(this.vcRef, this.record['id']).subscribe(response => {
      console.log(response);
    });
  }

  protected disabledCondition(controlName?): boolean {
    const disabled = this.mode === 'view' || (this.mode === 'edit' && controlName === 'key');
    return disabled;
  }

  submit() {
    this.processing = true;
    let keys = Object.keys(this.form.value);
    let features = {};
    keys.forEach(key => {
      if (key !== 'id' && key !== 'key' && key !== 'required' && this.form.value[key]) {
        features[key] = this.form.value[key];
      }
    });
    if (this.mode === 'new') {
      let data = {};
      data['id'] = this.form.value['id'];
      data['key'] = this.form.value['key'];
      data['description'] = this.form.value['description'];
      data['required'] = this.form.value['required'] ? "Y" : "N";
      data['defaultValue'] = this.form.value['defaultValue'];
      data['currentValue'] = this.form.value['currentValue'];
      data['dateFrom'] = this.form.value['dateFrom'];
      data['dateApplyFrom'] = this.form.value['dateApplyFrom'];
      data['programmedValue'] = this.form.value['programmedValue'];
      data['features'] = features;
      if (!this.validationControls()) {
        return;
      }
      this.dynaDataService.create(data).subscribe(res => {
        const title = this.translate.instant('title.information');
        const message = this.translate.instant('message.create.succesful');
        this.notificationService.showMessage(
          message,
          title,
          NotificationType.success
        );
        this.record = new Object();
        this.router.navigate([this.returnUrl]);
        this.form.reset();
        this.processing = false;
      }, error => { this.processing = false });
    } else {
      this.form.controls['key'].enable();
      this.record['key'] = this.form.value['key'];
      this.form.controls['key'].disable();
      this.record['description'] = this.form.value['description'];
      this.record['required'] = this.form.value['required'] ? "Y" : "N";
      this.record['defaultValue'] = this.form.value['defaultValue'];
      this.record['currentValue'] = this.form.value['currentValue'];
      this.record['dateFrom'] = this.form.value['dateFrom'];
      this.record['dateApplyFrom'] = this.form.value['dateApplyFrom'];
      this.record['programmedValue'] = this.form.value['programmedValue'];
      this.record['features'] = features;
      console.log(this.record);

      if (!this.validationControls()) {
        return;
      }
      this.dynaDataService.update(this.record['id'], this.record).subscribe(res => {
        const title = this.translate.instant('title.information');
        const message = this.translate.instant('message.update.succesful');
        this.notificationService.showMessage(
          message,
          title,
          NotificationType.success
        );
        this.form.markAsPristine();
        this.router.navigate([this.returnUrl]);
      });
    }
  }

  getDate() {
    if (this.record && this.record['required'] !== undefined && this.record['dateFrom'] === this.form.value['dateFrom']) {
      return this.form.value['dateFrom'];
    } else {
      let newDate = new Date();
      return newDate;
    }
  }

  toDate() {
    let newDate = new Date();
    if (this.form.value['dateFrom'] !== '') {
      if (this.form.value['dateFrom'] < newDate) {
        return newDate;
      } else {
        return this.form.value['dateFrom'];
      }
    } else {
      return newDate;
    }
  }

  updateControls(required) {
    this.isRequiredValueActivated = required;
    if (required) {
      this.form.addControl('defaultValue', new FormControl({ value: '', disabled: this.disabledCondition('defaultValue') }));
    } else {
      this.form.removeControl('defaultValue');
    }
  }

  ngOnInit() {
    super.ngOnInit();
    if (this.record && this.record['required'] !== undefined) {
      this.isRequiredValueActivated = this.record['required'] === 'Y';
    }
  }

  openToastr(value: string): void {
    const title = 'Mensaje de error';
    this.message = 'Debe ingresar un valor para "' + value + '"';
    this.notificationService.showMessage(
      this.message,
      title,
      NotificationType.error
    );
  }

  validationControls(): boolean {
    let validate = true;
    if (this.form.value['dateFrom'] === null) {
      this.form.controls['dateFrom'].setValue('');
    }
    if (this.form.value['dateApplyFrom'] === null) {
      this.form.controls['dateApplyFrom'].setValue('');
    }
    if (this.form.value['dateFrom'] !== '' && this.form.value['currentValue'] === '') {
      this.openToastr("Valor actual");
      validate = false;
    }

    if (this.form.value['dateFrom'] === '' && this.form.value['currentValue'] !== '') {
      this.openToastr("Desde");
      validate = false;
    }

    if (this.form.value['dateApplyFrom'] !== '' && this.form.value['programmedValue'] === '') {
      this.openToastr("Valor programado");
      validate = false;
    }
    if (this.form.value['dateApplyFrom'] === '' && this.form.value['programmedValue'] !== '') {
      this.openToastr("Aplica a partir de");
      validate = false;
    }
    return validate;
  }

  validatorProgrammed(event) {
    if (event !== '') {
      this.form.addControl('programmedValue', new FormControl({ value: this.getValueFromRecord('programmedValue'), disabled: this.disabledCondition('programmedValue') }));
      this.form.addControl('dateApplyFrom', new FormControl({ value: this.getValueFromRecord('dateApplyFrom'), disabled: this.disabledCondition('dateApplyFrom') }));
      this.flag = true;
    } else {
      if (this.form && this.form.controls['programmedValue'] && this.form.controls['dateApplyFrom']) {
        this.form.removeControl('programmedValue');
        this.form.removeControl('dateApplyFrom');
        console.log(this.form);
      }
      this.flag = false;
    }
  }
}
