import { Component, Input, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { FormArray, FormBuilder, FormGroup, Validators } from '@angular/forms';
import { SocServiceService } from '../../logic/services/soc-service.service';
import { FormHelper } from '../../ui/controls/form-helper';
import { AlertService } from '../../ui/infrastructure/alert.service';
import { SecurityService } from '../../logic/services/security.service';

@Component({
  selector: 'app-edit-soc-service',
  templateUrl: './edit-soc-service.component.html'
})
export class EditSocServiceComponent implements OnInit {

  @Input() _id: number;

  contextFormGroup: FormGroup;

  storing = false;

  private static buildFormGroup(fb: FormBuilder, data: any) {
    const fg = fb.group({
      id: data.id,
      caption: [data.caption, Validators.compose([Validators.required, Validators.maxLength(140)])],
      supplierIds: this.buildFormArray(fb, data.supplierIds),
      deliveryAreaId: [data.deliveryAreaId, Validators.required],
      parameterValues: this.buildFormArray(fb, []),
      legalInfoDescription: data.legalInfoDescription
    });

    if (data.parameterValues && data.parameterValues.length) {
      data.parameterValues.forEach(parameter => (fg.get('parameterValues') as FormArray).push(this.buildFormParameters(fb, parameter)));
    }

    return fg;
  }

  private static buildFormArray(fb: FormBuilder, data: any[]) {
    return fb.array(data || []);
  }

  private static buildFormParameters(fb: FormBuilder, data: any) {
    return fb.group({
      parameterId: data.parameterId,
      parameterValueIds: this.buildFormArray(fb, data.parameterValueIds || [])
    });
  }

  constructor(private route: ActivatedRoute,
              private router: Router,
              private fb: FormBuilder,
              private socServiceService: SocServiceService,
              private alertService: AlertService,
              public securityService: SecurityService) {

  }

  isInvalid(controlName: string) {
    return FormHelper.isInvalid(this.contextFormGroup, controlName);
  }

  getDisabledParameter() {
    return (this.contextFormGroup.get('parameterValues').value as any[]).map(value => value.parameterId);
  }

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

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

  ngOnInit() {
    this.route.paramMap
      .subscribe(params => {
        this._id = parseInt(params.get('id'), 10);
        if (this._id === 0) {
          this._id = null;
        }
        this.loadData();
      });
  }

  loadData() {
    if (this._id) {

      this.socServiceService.getSocServices$()
        .subscribe(socServices => {
          const socService = socServices.find(socServ => socServ.id === this._id);
          this.setData(socService);
        });
    } else {
      this.setData({});
    }
  }

  setData(data: any) {
    this.contextFormGroup = EditSocServiceComponent.buildFormGroup(this.fb, data);
  }

  store() {

    if (!this.contextFormGroup.valid) {
      FormHelper.setFocusToInvalidControl(this.contextFormGroup);
      return;
    }

    this.socServiceService.storeSocService(this.contextFormGroup.value)
      .subscribe(response => {
        this._id = response.id;
        this.socServiceService.clearSocServices();
        this.setData(response);
        this.alertService.success('Услуга сохранена');
      });
  }

  addParameter() {
    (this.contextFormGroup.get('parameterValues') as FormArray).push(EditSocServiceComponent.buildFormParameters(this.fb, {}));
    this.contextFormGroup.markAsDirty();
  }

  deleteParameter(index: number) {
    (this.contextFormGroup.get('parameterValues') as FormArray).removeAt(index);
    this.contextFormGroup.markAsDirty();
  }

  cancelEdit() {
    if (!this._id) {
      this.router.navigate(['list-soc-service']).then();
      return;
    } else {
      this.loadData();
    }
  }

  refreshData() {
    this.socServiceService.clearSocServices();
    this.loadData();
  }

  deleteSocService() {
    this.alertService.confirmModal('Вы уверены, что хотите удалить услугу?', 'Да')
      .subscribe(confirm => {
        if (confirm) {
          this.socServiceService.deleteSocService(this._id).subscribe({
            next: () => {
              this.alertService.success('Услуга удалена');
              this.socServiceService.clearSocServices();
              this.router.navigate(['list-soc-service']).then();
            },
            error: () => {
              this.alertService.error('Не удалось удалить услугу');
            }
          });
        }
      });
  }
}
