import {createContext, Dispatch} from "react";
import {get} from "../util/AjaxUtils.ts";
import {MessageInstance} from "antd/es/message/interface";

export enum GlobalDataActionType {
    REFRESH_SELF
}

export interface User {
    balance: string;
    nickname: string;
    userId: string;
    username: string;
    hasUserInfo: boolean;
}

export function reloadUser(messageApi: MessageInstance, globalDispatchContext: Dispatch<GlobalDataAction>) {
    return new Promise<any>(resolve => {
        get<any>({
            messageApi,
            url: '/api/user-info/get-user-self',
            onSuccess({data}) {
                globalDispatchContext({
                    type: GlobalDataActionType.REFRESH_SELF,
                    user: {
                        balance: (Math.floor(data.accountMoney) / 100).toFixed(2),
                        nickname: data.nickname,
                        userId: data.userId,
                        username: data.username,
                        hasUserInfo: data.hasUserInfo,
                    }
                })
                resolve(data);
            }
        })
    })
}

export interface GlobalData {
    user: User;
}

export interface GlobalDataAction {
    type: number;
    user?: User;
}

export const GlobalContext = createContext<GlobalData>({
    user: {
        balance: '0',
        nickname: '',
        userId: '',
        username: '',
        hasUserInfo: false
    }
});
export const GlobalDispatchContext = createContext<Dispatch<GlobalDataAction>>(() => {
});
