import { Component, inject, Inject } from '@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { TranslationService } from '@core/services/translation.service';
import { ToastrService } from 'ngx-toastr';
import { BaseComponent } from 'src/app/base.component';
import { PageStore } from '../page-store';
import { PageService } from '@core/services/page.service';
import { Page } from '@core/domain-classes/page';

@Component({
  selector: 'app-manage-page',
  templateUrl: './manage-page.component.html',
  styleUrls: ['./manage-page.component.scss'],
})
export class ManagePageComponent extends BaseComponent {
  name: string;
  url: string;
  isEdit: boolean = false;
  pageStore = inject(PageStore);
  constructor(
    public dialogRef: MatDialogRef<ManagePageComponent>,
    @Inject(MAT_DIALOG_DATA) public data: Page,
    private pageService: PageService,
    private toastrServoce: ToastrService,
    private translationService: TranslationService
  ) {
    super();
    if (this.data.id) {
      this.isEdit = true;
      this.name = this.data.name;
      this.url = this.data.url;
    }
  }

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

  savePage(): void {
    const page = {
      id: this.data.id,
      name: this.data.name,
      url: this.data.url,
    };
    if (page.id) {
      this.pageService.update(page).subscribe((d) => {
        this.toastrServoce.success(
          this.translationService.getValue('PAGE_UPDATED_SUCCESSFULLY')
        );
        this.pageStore.loadByQuery();
        this.dialogRef.close();
      });
    } else {
      this.pageService.add(page).subscribe(() => {
        this.toastrServoce.success(
          this.translationService.getValue('PAGE_ADDED_SUCCESSFULLY')
        );
        this.pageStore.loadByQuery();
        this.dialogRef.close();
      });
    }
  }
}
