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

import { request } from "../utils/request.js";
import { locationRestTemplatesBlockerUseGet } from "../wp-api/templatesBlockerUse.get.js";

import type { CookieStore } from "../store/cookie.js";
import type { ResponseRouteTemplatesBlockersGet } from "../wp-api/templatesBlocker.get.js";
import type {
    ParamsRouteTemplatesBlockerUseGet,
    RequestRouteTemplatesBlockerUseGet,
    ResponseRouteTemplatesBlockerUseGet,
} from "../wp-api/templatesBlockerUse.get.js";

class BlockerTemplate {
    @observable
    public busy = false;

    @observable
    public data: ResponseRouteTemplatesBlockersGet["items"][0];

    public readonly store: CookieStore;

    public constructor(template: BlockerTemplate["data"], store: CookieStore) {
        runInAction(() => {
            this.data = template;
        });
        this.store = store;
    }

    @observable
    public use: ResponseRouteTemplatesBlockerUseGet;

    public fetchUse: () => Promise<BlockerTemplate["use"]> = flow(function* (this: BlockerTemplate) {
        try {
            this.busy = true;
            const response: ResponseRouteTemplatesBlockerUseGet = yield request<
                RequestRouteTemplatesBlockerUseGet,
                ParamsRouteTemplatesBlockerUseGet,
                ResponseRouteTemplatesBlockerUseGet
            >({
                location: locationRestTemplatesBlockerUseGet,
                params: {
                    identifier: this.data.identifier,
                },
            });

            this.use = response;
            this.store.addServiceTemplates(response.consumerData.serviceTemplates);
            return this.use;
        } catch (e) {
            console.log(e);
            throw e;
        } finally {
            this.busy = false;
        }
    });
}

export { BlockerTemplate };
