package emu.nebula.server.handlers;

import emu.nebula.net.NetHandler;
import emu.nebula.net.NetMsgId;
import emu.nebula.proto.SkillInstanceSweep.SkillInstanceSweepReq;
import emu.nebula.proto.SkillInstanceSweep.SkillInstanceSweepResp;
import emu.nebula.proto.SkillInstanceSweep.SkillInstanceSweepRewards;
import emu.nebula.net.HandlerId;

import java.util.List;

import emu.nebula.data.GameData;
import emu.nebula.game.inventory.ItemParamMap;
import emu.nebula.game.quest.QuestCondition;
import emu.nebula.net.GameSession;

@HandlerId(NetMsgId.skill_instance_sweep_req)
public class HandlerSkillInstanceSweepReq extends NetHandler {

    @Override
    public byte[] handle(GameSession session, byte[] message) throws Exception {
        // Parse request
        var req = SkillInstanceSweepReq.parseFrom(message);
        
        // Get instance data
        var data = GameData.getSkillInstanceDataTable().get(req.getId());
        if (data == null) {
            return session.encodeMsg(NetMsgId.skill_instance_sweep_failed_ack);
        }
        
        // Sweep
        var change = session.getPlayer().getInstanceManager().sweepInstance(
                data,
                QuestCondition.SkillInstanceClearTotal,
                session.getPlayer().getProgress().getSkillInstanceLog(),
                0,
                req.getTimes()
        );
        
        // Sanity check
        if (change == null) {
            return session.encodeMsg(NetMsgId.skill_instance_sweep_failed_ack);
        }
        
        // Build response
        var rsp = SkillInstanceSweepResp.newInstance()
                .setChange(change.toProto());
        
        // Add reward list to response
        if (change.getExtraData() != null) {
            @SuppressWarnings("unchecked")
            var list = (List<ItemParamMap>) change.getExtraData();
            
            for (var rewards : list) {
                var reward = SkillInstanceSweepRewards.newInstance()
                        .setExp(data.getEnergyConsume());
                
                rewards.toItemTemplateStream().forEach(reward::addAwardItems);
                
                rsp.addRewards(reward);
            }
        }
        
        // Send response
        return session.encodeMsg(NetMsgId.skill_instance_sweep_succeed_ack, rsp);
    }

}
