import { Component } from "@angular/core";
import { NgbModal } from "@ng-bootstrap/ng-bootstrap";
import { ActionComponent } from "./action/action.component";
import { BaseCrudComponent } from "src/app/cores/class-templates/base-crud.component";
import {
  Bahan,
  BahanService,
} from "src/app/cores/api-services/gudang/bahan.service";
import { HelpersService } from "src/app/cores/services/helpers.service";
import { LoadingService } from "src/app/cores/services/loading.service";
import { Subject, takeUntil } from "rxjs";

@Component({
  selector: "app-gudang",
  templateUrl: "./gudang.component.html",
  styleUrls: ["./gudang.component.scss"],
})
export class GudangComponent extends BaseCrudComponent<Bahan> {
  dataInsertSubs$ = new Subject<void>();
  dataUpdateSubs$ = new Subject<void>();

  constructor(
    public override helpers: HelpersService,
    public override loading: LoadingService,
    public override api: BahanService,
    public override modal: NgbModal
  ) {
    super(helpers, loading, api, modal);

    this.searchFields = "name";
  }

  onCreate(): void {
    const modalRef = this.modal.open(ActionComponent);
    modalRef.componentInstance.action = "create";
    modalRef.result.then(
      (result) => {
        if (result) {
          this.api
            .insert(result)
            .pipe(takeUntil(this.dataInsertSubs$))
            .subscribe({
              next: () => {
                this.helpers.toast("success", "Data berhasil ditambahkan");
                this.getAll();
              },
              error: () => {
                this.helpers.toast("error", "Data gagal ditambahkan");
              },
            });
        }
      },
      () => {}
    );
  }

  onUpdate(data: Bahan): void {
    const modalRef = this.modal.open(ActionComponent);
    modalRef.componentInstance.action = "update";
    modalRef.componentInstance.data = data;
    modalRef.result.then(
      (result) => {
        if (result) {
          this.api
            .update(data.id, result)
            .pipe(takeUntil(this.dataUpdateSubs$))
            .subscribe({
              next: () => {
                this.helpers.toast("success", "Data berhasil diubah");
                this.getAll();
              },
              error: () => {
                this.helpers.toast("error", "Data gagal diubah");
              },
            });
        }
      },
      () => {}
    );
  }
}
