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

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

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
public class GetDeck extends ClientRequestParser {
    @Override
    public void parse(BattleNetPacket packet, ClientRequestBody body, TcpConnection conn) throws Exception {
        Protocol.GetDeckContents request = Protocol.GetDeckContents.parseFrom(body.getBody());

        Protocol.GetDeckContentsResponse.Builder deckContentsResponse = Protocol.GetDeckContentsResponse.newBuilder();
        List<Protocol.DeckCardData> l;
        for( long id : request.getDeckIdList() ) {
            l = conn.getUserService().getDeckContentForDeckId(conn.getUserId(), id)
                            .stream()
                            .map(c -> Protocol.DeckCardData.newBuilder()
                                    .setQty(1)
                                    .setHandle(0)
                                    .setPrev(0)
                                    .setDef(Protocol.CardDef.newBuilder()
                                            .setPremium(c.getIsPremium() ? 1 : 0)
                                            .setAsset(c.getAssetId().intValue()))
                                    .build())
                            .collect(Collectors.toList());
            deckContentsResponse.addDecks(
                    Protocol.DeckContents.newBuilder()
                    .setSuccess(true)
                    .setDeckId(id)
                    .addAllCards(l)
            );
        }
        Protocol.GetDeckContentsResponse dd = deckContentsResponse.build();

        Protocol.ClientResponse clResponse = Protocol.ClientResponse.newBuilder()
                .addAttribute(Protocol.Attribute.newBuilder()
                        .setName("id")
                        .setValue(Protocol.Variant.newBuilder()
                                .setIntValue(215)
                        ))
                .addAttribute(Protocol.Attribute.newBuilder()
                        .setName("proto")
                        .setValue(Protocol.Variant.newBuilder()
                                .setBlobValue(dd.toByteString())
                        ))
                .build();

        Protocol.Header header = Processor.generateResponse(clResponse.getSerializedSize(), packet.getHeader().getToken(), 0, 0);
        conn.send(new BattleNetPacket(header, clResponse.toByteArray()));
    }

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