import { computed } from "mobx";

import { AbstractPostCollection, ClientCollection, RouteHttpVerb } from "@devowl-wp/utils";

import { BlockerModel } from "./blockerModel.js";
import { request } from "../utils/request.js";

import type { CookieStore } from "../store/cookie.js";

@ClientCollection.annotate({
    path: "/rcb-blocker",
    singlePath: "/rcb-blocker/:id",
    namespace: "wp/v2",
    methods: [RouteHttpVerb.GET],
    request,
})
class BlockerCollection extends AbstractPostCollection<BlockerModel> {
    public readonly store: CookieStore;

    public constructor(store: CookieStore) {
        super();
        this.store = store;
    }

    @computed
    public get sortedBlockers() {
        const result = Array.from(this.entries.values());
        result.sort((a, b) => {
            if (a.data.menu_order < b.data.menu_order) {
                return -1;
            } else if (a.data.menu_order > b.data.menu_order) {
                return 1;
            } else {
                // a.menu_order === b.menu_order
                if (a.key < b.key) {
                    return 1;
                } else if (a.key > b.key) {
                    return -1;
                } else {
                    return 0;
                }
            }
        });
        return result;
    }

    public instance(response: BlockerModel["data"]): BlockerModel {
        return new BlockerModel(this).fromResponse(response);
    }
}

export { BlockerCollection };
