
import { DonationModel } from '../db/Donation';
import { getZeroPoint, nowSeconds } from '../pubUtils/timeUtil';
import { GuildModel } from '../db/Guild';
import { findWhere } from 'underscore';
import { GUILD_STRUCTURE } from '../consts/constModules/guildConst';
/**
 * 获得军团捐献，并检查是否刷新捐献数据
 * @param code 
 * @param serverId 
 */
export async function getDonation(code: string, serverId: number) {
    let donation = await DonationModel.getDonation(code);
    if (!donation) {
        donation = await createDonation(code, serverId);
    }
    if (donation.refTime < getZeroPoint()) {
        let { structure } = await GuildModel.findGuild(code, serverId, 'structure');
        let { lv } = findWhere(structure, {id: GUILD_STRUCTURE.DONATE});
        donation = await DonationModel.updateDonation(code, { donateFund:0, reports:[], refTime: nowSeconds(), donationLv: lv});
    }
    return donation;
}

/**
 * 创建军团捐献信息
 * @param code 
 * @param serverId 
 */
export async function  createDonation(code: string, serverId: number) {
    let { structure } = await GuildModel.findGuild(code, serverId, 'structure');
    let { lv } = findWhere(structure, {id: GUILD_STRUCTURE.DONATE});
    let donation = await DonationModel.createDonation(code, lv);
    return donation;
}