import { Component, inject, Inject, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { AppSetting } from '@core/domain-classes/app-setting';
import { AppSettingService } from '@core/services/app-setting.service';
import { TranslationService } from '@core/services/translation.service';
import { ToastrService } from 'ngx-toastr';
import { AppSettingsStore } from '../app-settings-store';
import { AppSettingModel } from './app-settings-model';

@Component({
  selector: 'app-app-settings-manage',
  templateUrl: './app-settings-manage.component.html',
  styleUrls: ['./app-settings-manage.component.css']
})
export class AppSettingsManageComponent implements OnInit {

  isEdit: boolean = false;
  appSettingForm: FormGroup<AppSettingModel>;
  appSetting: AppSetting;
  private appSettingsStore = inject(AppSettingsStore);
  public dialogRef = inject(MatDialogRef<AppSettingsManageComponent>);
  private toastrServoce = inject(ToastrService);
  private appSettingService = inject(AppSettingService);
  public data: AppSetting = inject(MAT_DIALOG_DATA);
  private fb = inject(FormBuilder);
  private translationService = inject(TranslationService);
  ngOnInit() {
    if (this.data) {
      this.isEdit = true;
      this.appSetting = this.data;
    }
    this.createForm();
    this.patchValue();
    this.appSettingValueChange();
  }

  appSettingValueChange() {
    if (!this.appSetting) {
      this.appSettingForm.get('name').valueChanges
        .subscribe(c => {
          const newKey = c.replace(/[^A-Z0-9]/ig, "_");
          this.appSettingForm.patchValue({
            key: newKey.toLowerCase()
          });
        });

      this.appSettingForm.get('key').valueChanges
        .subscribe(c => {
          const newKey = c.replace(/[^A-Z0-9]/ig, "_");
          if (newKey !== this.appSettingForm.get('key').value) {
            this.appSettingForm.patchValue({
              key: newKey.toLowerCase()
            });
          }
        })
    }
  }

  createForm() {
    this.appSettingForm = this.fb.group<AppSettingModel>({
      name: new FormControl('', [Validators.required]),
      key: new FormControl({ value: '', disabled: this.isEdit }, [Validators.required]),
      value: new FormControl('', [Validators.required]),
    })
  }
  patchValue() {
    if (this.appSetting) {
      this.appSettingForm.patchValue({
        name: this.appSetting.name,
        key: this.appSetting.key,
        value: this.appSetting.value
      });
    }
  }

  onCancel(): void {
    this.dialogRef.close();
  }

  buidForm(): AppSetting {
    const appSetting: AppSetting = {
      id: this.appSetting ? this.appSetting.id : null,
      name: this.appSettingForm.get('name').value,
      key: this.appSetting ? this.appSetting.key : this.appSettingForm.get('key').value,
      value: this.appSettingForm.get('value').value,
    };
    return appSetting;
  }

  saveAppSetting(): void {
    if (this.appSettingForm.valid) {
      if (this.appSetting) {
        this.appSettingService.updateAppSetting(this.buidForm())
          .subscribe(d => {
            this.toastrServoce.success(this.translationService.getValue('APPSETTING_UPDATED_SUCCESSFULLY'));
            this.appSettingsStore.loadByQuery();
            this.dialogRef.close();
          });
      } else {
        const key = this.appSettingForm.get('key').value;
        const newKey = key.replace(/[^A-Z0-9]/ig, "_");
        const appSettingFormValue = this.buidForm();
        appSettingFormValue.key = newKey.trim();
        this.appSettingService.addAppSetting(appSettingFormValue)
          .subscribe(() => {
            this.toastrServoce.success(this.translationService.getValue(`APPSETTING_SAVE_SUCCESSFULLY`));
            this.appSettingsStore.loadByQuery();
            this.dialogRef.close();
          });
      }
    } else {
      this.appSettingForm.markAllAsTouched();
    }
  }

}
