package com.alterdekim.hearthhack.component.processor.client.request;

import com.alterdekim.Protocol;
import com.alterdekim.hearthhack.component.TcpConnection;
import com.alterdekim.hearthhack.entity.Deck;
import com.alterdekim.hearthhack.util.BattleNetPacket;
import com.alterdekim.hearthhack.util.ClientRequestBody;
import lombok.extern.slf4j.Slf4j;

import static com.alterdekim.hearthhack.util.GameUtilities.generateNotification;

@Slf4j
public class CreateDeck extends ClientRequestParser {
    @Override
    public void parse(BattleNetPacket packet, ClientRequestBody body, TcpConnection conn) throws Exception {
        // DeckCreated 217

        Protocol.CreateDeck request = Protocol.CreateDeck.parseFrom(body.getBody());

        Deck d = conn.getUserService().createDeck(conn.getUserId(), request.getName(), request.getHero(), request.getHeroPremium() != 0);

        Protocol.DeckCreated response = Protocol.DeckCreated.newBuilder()
                .setInfo(Protocol.DeckInfo.newBuilder()
                        .setId(d.getId())
                        .setName(d.getName())
                        .setCardBack(conn.getUserService().getCardBackById(d.getCardBack()).getBackId())
                        .setHero(d.getHero())
                        .setDeckType(Protocol.DeckType.forNumber(d.getDeckType()))
                        .setValidity(767L)
                        .setHeroPremium(d.getHeroPremium() ? 1 : 0)
                        .setCardBackOverride(d.getCardBackOverride())
                        .setHeroOverride(d.getHeroOverride())
                        .setLastModified(d.getLastModified())
                        .setSortOrder(d.getSortOrder())
                        .setSourceType(Protocol.DeckSourceType.forNumber(d.getSourceType()))
                        .build()
                ).build();

        Protocol.Notification n = generateNotification(217, response.toByteString(), response.getSerializedSize());

        Protocol.Header header = Protocol.Header.newBuilder()
                .setServiceId(4)
                .setMethodId(1)
                .setToken(conn.nextToken())
                .setObjectId(0)
                .setSize(n.getSerializedSize())
                .setStatus(0)
                .build();

        conn.send(new BattleNetPacket(header, n.toByteArray()));
    }

    @Override
    public int getId() {
        return 209;
    }
}
