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

import { request } from "../utils/request.js";
import { locationRestTemplatesServiceUseGet } from "../wp-api/templatesServiceUse.get.js";

import type { CookieStore } from "../store/cookie.js";
import type { ResponseRouteTemplatesServicesGet } from "../wp-api/templatesServices.get.js";
import type {
    ParamsRouteTemplatesServiceUseGet,
    RequestRouteTemplatesServiceUseGet,
    ResponseRouteTemplatesServiceUseGet,
} from "../wp-api/templatesServiceUse.get.js";

class ServiceTemplate {
    @observable
    public busy = false;

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

    @observable
    public use: ResponseRouteTemplatesServiceUseGet;

    public readonly store: CookieStore;

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

    public fetchUse: () => Promise<ServiceTemplate["use"]> = flow(function* (this: ServiceTemplate) {
        try {
            this.busy = true;
            const response: ResponseRouteTemplatesServiceUseGet = yield request<
                RequestRouteTemplatesServiceUseGet,
                ParamsRouteTemplatesServiceUseGet,
                ResponseRouteTemplatesServiceUseGet
            >({
                location: locationRestTemplatesServiceUseGet,
                params: {
                    identifier: this.data.identifier,
                },
            });

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

export { ServiceTemplate };
