import { Component } from '@angular/core';
import { SettingsApiService } from '@fleio-api/core/settings-api.service';
import { UntypedFormBuilder } from '@angular/forms';
import { NotificationService } from '@shared/ui-api/notification.service';
import { DetailsComponentBase } from '@objects-view/details-component-base';
import { IBaseFleioObjectModel } from '@fleio-api/base-model/base-fleio-object.model';
import { IFormattingSettingsModel } from '@fleio-api/core/model/formatting-settings.model';
import { ConfigService } from '@shared/config/config.service';

@Component({
  selector: 'app-formatting-settings',
  templateUrl: './formatting-settings.component.html',
  styleUrls: ['./formatting-settings.component.scss']
})
export class FormattingSettingsComponent extends DetailsComponentBase<IBaseFleioObjectModel> {
  formattingSettingsForm = this.formBuilder.group({
    currency_display_mode: [null],
    date_format: [null],
    date_time_format: [null],
  });
  loading = false;
  today = new Date().toISOString();
  private formattingSettings: IFormattingSettingsModel;

  constructor(
    private settingsApi: SettingsApiService,
    private formBuilder: UntypedFormBuilder,
    private notificationService: NotificationService,
    public config: ConfigService,
  ) {
    super();
  }

  protected initTabData() {
    this.loading = true;
    this.settingsApi.getFormattingSettings().subscribe(formattingSettings => {
      this.formattingSettings = formattingSettings;
      this.formattingSettingsForm.patchValue(formattingSettings);
    }, error => {
      if (error.status === 403) {
        this.formattingSettingsForm.disable();
      }
    }).add(() => {
      this.loading = false;
    });
  }

  saveSettings() {
    const formattingSettings = this.formattingSettingsForm.value;
    this.objectController.loading = true;
    this.settingsApi.saveFormattingSettings(formattingSettings).subscribe(() => {
      this.notificationService.showMessage($localize`Formatting settings saved`);
    }, () => {
      this.notificationService.showMessage($localize`Failed to save formatting settings, check logs for details`);
    }).add(() => {
      this.objectController.loading = false;
    });
  }
}
