import { Component, Input, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { AbstractControl, FormBuilder, Validators } from '@angular/forms';
import { SupplierService } from '../../logic/services/supplier.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-supplier',
  templateUrl: './edit-supplier.component.html'
})
export class EditSupplierComponent implements OnInit {

  @Input() _id: number;
  storing = false;

  contextFormGroup = EditSupplierComponent.buildFormGroup(this.fb, {});

  private static buildFormGroup(fb: FormBuilder, data: any) {
    return fb.group({
      id: data.id,
      caption: [data.caption, Validators.compose([Validators.required, Validators.maxLength(140)])],
      description: [data.description, Validators.required],
      address: [data.address, Validators.required],
      workSchedules: [data.workSchedules, Validators.required],
      phones: [data.phones, Validators.compose([Validators.pattern('^[0-9\\-\\s(),]+$'), Validators.required])],
      email: [data.email, Validators.required],
      website: [data.website, Validators.required],
      latitude: [data.latitude, Validators.compose([Validators.min(-90), Validators.max(90), Validators.required])],
      longitude: [data.longitude, Validators.compose([Validators.min(-180), Validators.max(180), Validators.required])]
    });
  }

  constructor(private route: ActivatedRoute,
              private router: Router,
              private fb: FormBuilder,
              private supplierService: SupplierService,
              private alertService: AlertService,
              public securityService: SecurityService) {
  }

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

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

  store() {

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

    this.supplierService.storeSupplier(this.contextFormGroup.value)
      .subscribe(response => {
        this.supplierService.clearSuppliers();
        this._id = response.id;
        this.contextFormGroup = EditSupplierComponent.buildFormGroup(this.fb, response);
        this.alertService.success('Поставщик сохранен');
      });
  }

  loadData() {
    if (this._id) {
      const existing = this.supplierService.getSupplierById(this._id);
      this.contextFormGroup = EditSupplierComponent.buildFormGroup(this.fb, existing);
    } else {
      this.contextFormGroup = EditSupplierComponent.buildFormGroup(this.fb, {});
    }
  }

  refreshFormData() {
    this.loadData();
  }

  cancelEdit() {
    this.loadData();
  }

  deleteSupplier() {
    this.alertService.confirmModal('Вы уверены, что хотите удалить поставщика?', 'Да')
      .subscribe(confirm => {
        if (confirm) {
          this.supplierService.deleteSupplier(this._id).subscribe({
            next: () => {
              this.alertService.success('Поставщик удален');
              this.supplierService.clearSuppliers();
              this.router.navigate(['list-supplier']).then();
            },
            error: () => {
              this.alertService.error('Не удалось удалить поставшика');
            }
          });
        }
      });
  }

  changeLocation(fg: AbstractControl, maxNumberLength: number) {
    const negativeCoordinate = fg.value.startsWith('-');
    const value = fg && fg.value ? fg.value.replaceAll(',', '.').split('.') : [];

    fg.setValue(null);
    if (value.length === 0) {
      fg.setValue('00.000000');
      return;
    }

    if (negativeCoordinate) {
      if (value[0].length < (maxNumberLength + 1)) {
        fg.setValue(value[0]);
      } else {
        fg.setValue('-' + value[0].substring(value[0].length - maxNumberLength, value[0].length));
      }
    } else {
      if (value[0].length <= maxNumberLength) {
        fg.setValue(value[0]);
      } else {
        fg.setValue(value[0].substring(value[0].length - maxNumberLength, value[0].length));
      }
    }

    if (value.length === 1) {
      fg.setValue(fg.value + '.000000');
    } else {
      fg.setValue(value[1].length > 6
      ? fg.value + '.' + value[1].substring(0, 6)
      : value[1].length < 6 ? fg.value + '.' + value[1].padEnd(6, '0') : fg.value + '.' + value[1]);
    }
  }
}
