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

import com.alterdekim.Protocol;
import com.alterdekim.hearthhack.component.TcpConnection;
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 SetCardBack extends ClientRequestParser {
    @Override
    public void parse(BattleNetPacket packet, ClientRequestBody body, TcpConnection conn) throws Exception {
        Protocol.SetCardBack request = Protocol.SetCardBack.parseFrom(body.getBody());
        Integer cardBack = request.getCardBack();
        boolean success = false;
        if( !request.hasDeckId() && conn.getUserService().isUserHasCardBack(conn.getUserId(), cardBack) ) {
            conn.getUserService().setDefaultUserCardBack(conn.getUserId(), cardBack);
            success = true;
        }

        Protocol.SetCardBackResponse response = Protocol.SetCardBackResponse.newBuilder()
                .setSuccess(success)
                .setCardBack(cardBack)
                .build();

        Protocol.Notification n = generateNotification(292, 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 291;
    }
}
