import { action, flow, observable } from "mobx";

import { PluginUpdate } from "../models/pluginUpdate.js";
import { request } from "../utils/request.js";
import { locationRestPluginUpdateGet } from "../wp-api/pluginUpdate.get.js";

import type { RootStore } from "./stores.js";
import type {
    ParamsRoutePluginUpdateGet,
    RequestRoutePluginUpdateGet,
    ResponseRoutePluginUpdateGet,
} from "../wp-api/pluginUpdate.get.js";

class PluginUpdateStore {
    @observable
    public busy = false;

    @observable
    public modalPlugin: string;

    @observable
    public pluginUpdates = new Map<string, PluginUpdate>();

    @observable
    public pluginUpdateFetchErrors = new Map<string, any>();

    public readonly rootStore: RootStore;

    public constructor(rootStore: RootStore) {
        this.rootStore = rootStore;
    }

    @action
    public hideModal() {
        this.modalPlugin = undefined;
    }

    public showInModal: (slug: string) => Promise<void> = flow(function* (this: PluginUpdateStore, slug) {
        this.modalPlugin = slug;
        try {
            yield this.fetchPluginUpdate(slug);
        } catch (e) {
            console.log(e);
            throw e;
        }
    });

    public fetchPluginUpdate: (slug: string) => Promise<PluginUpdate> = flow(function* (this: PluginUpdateStore, slug) {
        this.busy = true;
        try {
            const result: ResponseRoutePluginUpdateGet = yield request<
                RequestRoutePluginUpdateGet,
                ParamsRoutePluginUpdateGet,
                ResponseRoutePluginUpdateGet
            >({
                location: locationRestPluginUpdateGet,
                params: {
                    slug,
                },
            });

            const pluginUpdate = new PluginUpdate(result, this);
            this.pluginUpdates.set(slug, pluginUpdate);
            this.pluginUpdateFetchErrors.delete(slug);
            return pluginUpdate;
        } catch (e) {
            console.log(e);
            this.pluginUpdateFetchErrors.set(slug, e);
            throw e;
        } finally {
            this.busy = false;
        }
    });
}

export { PluginUpdateStore };
