import {Component, OnInit} from '@angular/core';
import {FormHelper} from '../../ui/controls/form-helper';
import {FormArray, FormBuilder, FormGroup} from '@angular/forms';
import {ParameterService} from '../../logic/services/parameter.service';
import {AlertService} from '../../ui/infrastructure/alert.service';
import {SecurityService} from '../../logic/services/security.service';

@Component({
  selector: 'app-edit-parameters',
  templateUrl: './edit-parameters.component.html',
  styleUrls: ['./edit-parameters.component.css']
})
export class EditParametersComponent implements OnInit {
  contextFormGroup: FormArray;
  sourceData = [];

  selectedId = this.fb.group({
    id: null,
    caption: ''
  });
  lookupItems = [];

  deletedParameterIds = [];

  private static buildFormParameter(fb: FormBuilder, data: any) {
    return fb.group({
      id: data.id,
      caption: data.caption,
      code: data.code,
      iconName: data.iconName,
      parameterValues: data.parameterValues || fb.array([])
    });
  }

  private static buildFormParameterValue(fb: FormBuilder, data: any) {
    return fb.group({
      id: data.id,
      caption: data.caption,
      parameterId: data.parameterId
    });
  }

  constructor(private fb: FormBuilder,
              private parameterService: ParameterService,
              private alertService: AlertService,
              public securityService: SecurityService) {
  }

  ngOnInit() {
    this.refreshFormData();
  }

  refreshFormData() {
    this.parameterService.clearParameters();
    this.parameterService.getParameters$()
      .subscribe(parameters => {
        this.sourceData = parameters;
        this.buildParameters(parameters);
      });
  }

  buildParameters(parameters: any[]) {
    this.contextFormGroup = this.fb.array([]);
    this.lookupItems = [];
    this.deletedParameterIds = [];

    parameters.forEach(parameter => {

      this.lookupItems.push({
        id: parameter.parameter.id,
        caption: parameter.parameter.caption
      });

      const values = this.fb.array([]);

      parameter.parameterValues.sort((a, b) => a.id - b.id);

      parameter.parameterValues.forEach(value => values.push(EditParametersComponent.buildFormParameterValue(this.fb, value)));

      const data = EditParametersComponent.buildFormParameter(this.fb, parameter.parameter);

      data.controls['parameterValues'] = values;

      this.contextFormGroup.push(data);
    });
  }

  defaultSelectedItem() {
    this.selectedId.patchValue({id: null, caption: ''});
  }

  controlToFormGroup(fg: any) {
    return fg as FormGroup;
  }

  getFormArray(fa: any) {
    return fa as FormArray;
  }

  changeItemSelected() {
    const indexEmptyParameter = this.contextFormGroup.controls.findIndex(par => !par.get('caption').value);

    if (indexEmptyParameter >= 0) {
      this.contextFormGroup.removeAt(indexEmptyParameter);
    }
  }

  isInvalid(formGroup: FormGroup, controlName: string): boolean {
    return FormHelper.isInvalid(formGroup, controlName);
  }

  createNewParameter() {
    this.defaultSelectedItem();
    this.contextFormGroup.push(EditParametersComponent.buildFormParameter(this.fb, {}));
  }

  deleteParameter(id: number, contextIndex: number) {

    this.alertService.confirmModal('Вы уверены, что хотите удалить параметр?', 'Да')
      .subscribe(confirm => {
        if (confirm) {
          if (id) {
            this.deletedParameterIds.push(id);
            const lookupIndex = this.lookupItems.findIndex(item => item.id == id);
            this.lookupItems.splice(lookupIndex, 1);
            this.defaultSelectedItem();
            this.alertService.success('Параметр будет удален после сохранения');
          }
          this.contextFormGroup.removeAt(contextIndex);
        }
      });
  }

  createNewParameterValue(parameter: FormGroup) {
    (parameter.get('parameterValues') as FormArray).push(EditParametersComponent.buildFormParameterValue(this.fb, {parameterId: parameter.get('id').value}));
  }

  deleteParameterValue(parameter: FormGroup, index: number) {
    (parameter.get('parameterValues') as FormArray).removeAt(index);
  }

  storeParameters() {
    const data = [];
    this.contextFormGroup.controls.forEach(par => data.push({
      parameter: {
        id: par.get('id').value,
        caption: par.get('caption').value,
        code: par.get('code').value,
        iconName: par.get('iconName').value
      },
      parameterValues: par.get('parameterValues').value
    }));

    this.parameterService.storeParameters({
      parameters: data,
      deletedParameterIds: this.deletedParameterIds
    })
      .subscribe(parameters => {
        this.sourceData = parameters;
        this.buildParameters(parameters);
        this.parameterService.clearParameters();
        this.alertService.success('Параметры сохранены.');
      });
  }

  cancel() {
    this.buildParameters(this.sourceData);
  }

  checkActiveButtonIconName(parameter: FormGroup, iconName: string) {

    if (!parameter.get('iconName').value) {
      parameter.get('iconName').setValue('icon_default.png');
    }

    return parameter.get('iconName').value == iconName;
  }

  changeIcon(parameter: FormGroup, newIconName: string) {
    parameter.get('iconName').setValue(newIconName);
  }
}
