import { mailInit, setMails, GMMail } from '../gmData/gmMail';
import { nowSeconds } from '../timeUtil';
const ALL_SERVER = 0;
export let gmData:any = {};
export async function init() {
    gmData.mails = await mailInit();
}

export function getGmMails(updatedMailAt: number, serverId: number) {
    let list = [];
    let nowTime = nowSeconds();
    let serverIds = [serverId, ALL_SERVER];
    for (let serverId of serverIds) {
        let gmServerData = gmData.mails.get(serverId);
        if (!gmServerData) 
            continue;
            gmServerData.forEach((gmMail)=>{
            if (gmMail.updatedAt >= updatedMailAt || gmMail.sendTime > updatedMailAt || gmMail.endTime > nowTime )
                list.push(gmMail);
        });
    }
    return list;
}

export function getUseGmMails(serverId: number) {
    let list = new Map<string, GMMail>();
    let serverIds = [serverId, ALL_SERVER];
    let nowTime = nowSeconds();
    for (let serverId of serverIds) {
        let gmServerData = gmData.mails.get(serverId);
        if (!gmServerData) 
            continue;
        gmServerData.forEach((gmMail)=>{
            if (gmMail.endTime > nowTime)
                list.set(gmMail.id, gmMail);
        });
    }
    return list;
}

export function getGmMailById(id: string, serverId: number, nowTime: number) {
    let gmMail;
    if (!!gmData.mails.get(serverId)) {
        gmMail = gmData.mails.get(serverId).get(id);
    }
    if (!gmMail) {
        if (!!gmData.mails.get(ALL_SERVER)) {
            gmMail = gmData.mails.get(ALL_SERVER).get(id);
        }
    }
    if (!gmMail || gmMail.endTime < nowTime)
        return null;
    return gmMail;
}

export function setGmMails(mails: GMMail[]) {
    setMails(mails, gmData.mails);
}


export function getGmUseMails(serverId: number) {
    let list = new Map<number, any>();
    if (!!gmData.mails.get(serverId)) {
        list =  gmData.mails.get(serverId);
    }
    let serverMail = gmData.mails.get(ALL_SERVER);
    if (!!serverMail) {
        list = Object.assign(list, serverMail);
    }
    return list;
}