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

import { __ } from "../utils/i18n.js";
import { request } from "../utils/request.js";
import { locationRestScannerResultIgnorePost } from "../wp-api/scannerResultIgnore.post.js";

import type { ScannerStore } from "../store/scanner.js";
import type {
    ParamsRouteScannerResultIgnorePost,
    RequestRouteScannerResultIgnorePost,
    ResponseRouteScannerResultIgnorePost,
} from "../wp-api/scannerResultIgnore.post.js";
import type { ResponseRouteScannerResultExternalsGet } from "../wp-api/scannerResultsExternal.get.js";

class ScannerResultExternalUrl {
    @observable
    public busy = false;

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

    @computed
    public get identifier() {
        return this.data.host;
    }

    @computed
    public get inactive() {
        return this.blockedStatus === "full" || this.data.ignored;
    }

    @computed
    public get blockedStatus() {
        const { foundCount, blockedCount } = this.data;
        return blockedCount === 0 ? "none" : foundCount === blockedCount ? "full" : "partial";
    }

    @computed
    public get blockedStatusText() {
        switch (this.blockedStatus) {
            case "full":
                return __("Fully blocked");
            case "partial":
                return __("Partially blocked");
            default:
                return __("Not blocked");
        }
    }

    public readonly store: ScannerStore;

    public constructor(externalUrl: ScannerResultExternalUrl["data"], store: ScannerStore) {
        runInAction(() => {
            this.data = externalUrl;
        });
        this.store = store;
    }

    public ignore: (state: boolean) => Promise<void> = flow(function* (this: ScannerResultExternalUrl, state) {
        this.busy = true;

        try {
            yield request<
                RequestRouteScannerResultIgnorePost,
                ParamsRouteScannerResultIgnorePost,
                ResponseRouteScannerResultIgnorePost
            >({
                location: locationRestScannerResultIgnorePost,
                request: {
                    type: "host",
                    value: this.data.host,
                    ignored: state,
                },
            });

            this.data.ignored = state;
        } catch (e) {
            console.log(e);
            throw e;
        } finally {
            this.busy = false;
        }
    });
}

export { ScannerResultExternalUrl };
