import { makeAutoObservable } from "mobx";
import { IDeviceDto } from "../types";
import { HomePageService } from "../services/HomePageService";
import { error, info } from "../../../utils/ToastHelper";

class HomePageStore {

    devices: IDeviceDto[] = []
    isLoading: boolean = false;
    isEditModalOpened: boolean = false;
    editModalCurrentId: number | null = null;
    currentEditDevice: IDeviceDto | undefined;


    constructor() {
        makeAutoObservable(this);
    }

    setEditModalOpened(id: number, isOpened: boolean): void {
        this.currentEditDevice = { ...this.devices.find(device => device.id === id) } as IDeviceDto;
        this.isEditModalOpened = isOpened;
    }

    setCurrentEditDevice(value: IDeviceDto | undefined) {
        this.currentEditDevice = value;
    }

    setDevices(value: IDeviceDto[]) {
        this.devices = value;
    }

    async loadDevices() {
        this.isLoading = true;
        const result = await HomePageService.getDeviceList();
        this.setDevices(result);
        this.isLoading = false;
    }

    async updateDevice(value: IDeviceDto) {
        const result = await HomePageService.updateDevice(value);
        if (result === null) {
            error("Ошибка", "Запрос не был выполнен");
            return;
        }

        this.setCurrentEditDevice(undefined);
        info("Успешно", "Изменения были сохранены")
        await this.loadDevices();
    }

    async deleteDevice(value: number) {
        const result = await HomePageService.deleteDevice(value);
        if (result === null) {
            error("Ошибка", "Запрос не был выполнен");
            return;
        }

        info("Успешно", "Устройство было удалено");
        await this.loadDevices();
    }
}

export const homePageStore = new HomePageStore();