import {
    makeAutoObservable,
    runInAction,
} from 'mobx';

import { rpc } from '../api/request';
import {
    ModeFWEnum,
    ShmChannelType,
    ShmFastAnswerType,
} from '../api/types';

class Store {
    constructor() {
        makeAutoObservable(this);
    }

    fastAnswers: ShmFastAnswerType[] = [];


    loadFastAnswers() {

        if (this.mode != "full") {
            return;
        }

        rpc.fastAnswers().then(({ result: data }) => {
            this.fastAnswers = data ?? [];
        });
    }

    mode: ModeFWEnum = "widget";

    setMode(mode: ModeFWEnum) {
        this.mode = mode;
    }

    isFixedChannel: boolean = false;

    setIsFixedChannel(isFixedChannel: boolean) {
        this.isFixedChannel = isFixedChannel;
    }



    userID: string | null = null;

    loadUser() {
        return new Promise((resolve) => {
            rpc.profileID().then(({ result: data }) => {

                this.userID = data ?? null;
                resolve(true);
            });
        });
    }



    isMobile = () => {
        return window.innerWidth < 768 || this.cap;
    }

    //Проверка на Capacitor
    cap: boolean = false;

    setCap(cap: boolean) {
        this.cap = cap;
    }

    channelTab: "member" | "join" = "member";

    setChannelTab(tab: "member" | "join") {
        this.channelTab = tab;
    }

    selectChannel: ShmChannelType | null = null;

    setSelectChannel(channel: ShmChannelType | null) {
        this.selectChannel = channel;
    }

    dialogsLoading = false;
    channelList: ShmChannelType[] = [];
    channelListLastMaxUpdated: number | null = null;
    joinChannelListLastMaxUpdated: number | null = null;
    channelListPollingInterval: ReturnType<typeof setInterval> | null = null;

    loadChannelList() {
        const isInitialLoad = this.channelList.length === 0;
        if (isInitialLoad) {
            this.dialogsLoading = true;
        }

        const isMember = !this.channelTab || this.channelTab === "member";
        const promise = isMember
            ? rpc.channelList({}, ["shmChannelMessages"])
            : rpc.joinChannelList({}, ["shmChannelMessages"]);

        promise
            .then(({ result: data }) => {
                runInAction(() => {
                    this.channelList = data?.data ?? [];
                    if (isMember) {
                        this.channelListLastMaxUpdated = data?.lastMaxUpdated ?? null;
                    } else {
                        this.joinChannelListLastMaxUpdated = data?.lastMaxUpdated ?? null;
                    }
                });
            })
            .finally(() => {
                runInAction(() => {
                    if (isInitialLoad) {
                        this.dialogsLoading = false;
                    }
                });
            });
    }

    startChannelListPolling() {
        this.stopChannelListPolling();
        const CHECK_INTERVAL_MS = 5000;

        this.channelListPollingInterval = setInterval(() => {
            const isMember = !this.channelTab || this.channelTab === "member";
            const checkApi = isMember
                ? rpc.channelListLastMaxUpdated
                : rpc.joinChannelLastMaxUpdated;

            checkApi().then(({ result: newValue }) => {
                const currentValue = isMember
                    ? this.channelListLastMaxUpdated
                    : this.joinChannelListLastMaxUpdated;

                if (newValue != null && newValue !== currentValue) {
                    this.loadChannelList();
                }
            });
        }, CHECK_INTERVAL_MS);
    }

    stopChannelListPolling() {
        if (this.channelListPollingInterval) {
            clearInterval(this.channelListPollingInterval);
            this.channelListPollingInterval = null;
        }
    }
}

export default new Store();
