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

import { request } from "../utils/request.js";
import { locationRestStatsGet } from "../wp-api/stats.get.js";

import type { RootStore } from "./stores.js";
import type { ParamsRestStatsGet, RequestRestStatsGet, ResponseRestStatsGet } from "../wp-api/stats.get.js";

type CancellablePromise<R> = ReturnType<ReturnType<typeof flow<R, any>>>;

class StatsStore {
    @observable
    public busy = false;

    @observable
    public deletableSpaceFormat = "0 B";

    @observable
    public deletableSpace = 0;

    @observable
    public newThumbnailsCount = 0;

    @observable
    public imagesCount = 0;

    @observable
    public totalCount = 0;

    @observable
    public sizes: ResponseRestStatsGet["sizes"] = {};

    @observable
    public schema = "";

    public readonly rootStore: RootStore;

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

    public fetch: () => CancellablePromise<void> = flow(function* (this: StatsStore) {
        this.busy = true;

        try {
            const result: ResponseRestStatsGet = yield request<
                RequestRestStatsGet,
                ParamsRestStatsGet,
                ResponseRestStatsGet
            >({
                location: locationRestStatsGet,
            });

            set(this, result);
        } catch (e) {
            console.log(e);
        } finally {
            this.busy = false;
        }
    });
}

export { StatsStore };
