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

import type { TcfVendorConfigurationRestrictivePurposes } from "@devowl-wp/cookie-consent-web-client";

import type { TcfStore } from "../store/tcf.js";
import type { ResponseRouteTcfVendorsGet } from "../wp-api/tcfVendors.get.js";

class TcfVendor {
    @observable
    public data: ResponseRouteTcfVendorsGet["vendors"][0];

    /**
     * Get existing vendor configuration for this vendor.
     */
    @computed
    public get vendorConfiguration() {
        for (const c of this.store.vendorConfigurations.entries.values()) {
            if (c.vendorModel?.data.id === this.data.id) {
                return c;
            }
        }
        return undefined;
    }

    /**
     * Calculate a map of restrictions for this vendor. This can be used to make a form
     * configurable depending on the current vendor.
     */
    @computed
    public get restrictivePurposes() {
        const result: TcfVendorConfigurationRestrictivePurposes = { normal: {} };
        for (const purpose of [...this.legIntPurposes, ...this.purposes]) {
            result.normal[purpose.data.id.toString()] = {
                enabled: true,
                legInt: this.legIntPurposes.indexOf(purpose) > -1 && !purpose.special ? "yes" : "no",
            };
        }
        return result;
    }

    /**
     * Map the integers to valid declaration objects.
     */
    @computed
    public get purposes() {
        return this.data?.purposes.map((id) => this.store.purposes.get(`${id}`));
    }

    @computed
    public get legIntPurposes() {
        return this.data?.legIntPurposes.map((id) => this.store.purposes.get(`${id}`));
    }

    @computed
    public get specialPurposes() {
        return this.data?.specialPurposes.map((id) => this.store.specialPurposes.get(`${id}`));
    }

    @computed
    public get features() {
        return this.data?.features.map((id) => this.store.features.get(`${id}`));
    }

    @computed
    public get specialFeatures() {
        return this.data?.specialFeatures.map((id) => this.store.specialFeatures.get(`${id}`));
    }

    @computed
    public get dataCategories() {
        return this.data?.dataDeclaration.map((id) => this.store.dataCategories.get(`${id}`));
    }

    public readonly store: TcfStore;

    public constructor(data: TcfVendor["data"], store: TcfStore) {
        runInAction(() => {
            this.data = data;
        });
        this.store = store;
    }
}

export { TcfVendor };
