import { ACTIVITY_TYPE, STATUS } from "../../consts";
import { ActivityModelType } from "../../db/Activity";
import { ActivityTaskPassModel } from "../../db/ActivityTaskPass";
import { RoleModel } from "../../db/Role";
import { TaskPassData } from "../../domain/activityField/taskPassField";
import { getRoleCreateTime, getServerCreateTime } from "../redisService";
import { getActivityById } from "./activityService";

export async function getTaskPassData(activityId: number, serverId: number, roleId: string) {
    let activityData = await getActivityById(activityId);

    let createTime = await getRoleCreateTime(roleId);
    let serverTime = await getServerCreateTime(serverId);
    let playerData = new TaskPassData(activityData, createTime, serverTime);
    let record = await ActivityTaskPassModel.findData(serverId, activityId, roleId, playerData.roundIndex);

    playerData.setPlayerRecord(record);

    return playerData;
}

export async function getTaskPassDataShow(activityId: number, serverId: number, roleId: string) {
    let playerData = await getTaskPassData(activityId, serverId, roleId);
    if(playerData && playerData.canShow && playerData.canShow()) {
        return playerData.getShowResult();
    }
    return null
}


/**
   * 购买高级战令
   *
   * @param {number} serverId 区Id
   * @param {number} activityId 活动Id
   * @param {string} roleId 角色Id
   * @param {string} productID 商品ID
   *
   */
 export async function makeTaskPass(roleId: string, roleName: string, sid: string, serverId: number, activityId: number, productID: string) {
    let activityData: ActivityModelType = await getActivityById(activityId);
    if (!activityData) {
        return STATUS.ACTIVITY_MISSING;
    }
    if (activityData.type !== ACTIVITY_TYPE.TASK_PASS) {
        return STATUS.ACTIVITY_TYPE_ERROR;
    }
    let createTime = await getRoleCreateTime(roleId);
    let serverTime = await getServerCreateTime(serverId);
    let playerData = new TaskPassData(activityData, createTime, serverTime);
    let roundIndex = playerData.roundIndex;
    await ActivityTaskPassModel.buy(serverId, activityId, roleId, roundIndex, productID);
    return {
        code: 0,
        data: Object.assign({}, { item: { roundIndex }, activityId: activityId })
    }
}

/**
   * 任务活动完成后会获得点数
   *
   * @param {number} serverId 区Id
   * @param {number} activityId 活动Id
   * @param {string} roleId 角色Id
   *
   */
export async function addTaskPassPoint(serverId: number, activityId: number, roleId: string, addPoint: number) {
    let activity = await getActivityById(activityId);
    if(!activity) return 0;
    let createTime = await getRoleCreateTime(roleId);
    let serverTime = await getServerCreateTime(serverId);
    let data = new TaskPassData(activity, createTime, serverTime);
    let result = await ActivityTaskPassModel.addPoint(serverId, activityId, roleId, data.roundIndex, addPoint);
    return result.totalPoint;   
}