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 java.util.stream.IntStream;

import static com.alterdekim.Protocol.ProductType.PRODUCT_TYPE_BOOSTER;
import static com.alterdekim.hearthhack.util.GameUtilities.generateNotification;

@Slf4j
public class PurchaseWithGold extends ClientRequestParser {

    private final int PACK_COST = 100;

    @Override
    public void parse(BattleNetPacket packet, ClientRequestBody body, TcpConnection conn) throws Exception {
        // PurchaseWithGoldResponse 280
        Protocol.PurchaseWithGold request = Protocol.PurchaseWithGold.parseFrom(body.getBody());
        Protocol.PurchaseWithGoldResponse response;
        if( request.getProduct() != PRODUCT_TYPE_BOOSTER ) {
            response = Protocol.PurchaseWithGoldResponse.newBuilder()
                    .setResult(Protocol.PurchaseWithGoldResponse.PurchaseResult.PR_FEATURE_NA)
                    .build();
        } else if( conn.getUserService().getGoldForUserId(conn.getUserId()) < (PACK_COST * request.getQuantity()) ) {
            response = Protocol.PurchaseWithGoldResponse.newBuilder()
                    .setResult(Protocol.PurchaseWithGoldResponse.PurchaseResult.PR_INSUFFICIENT_FUNDS)
                    .build();
        } else {
            IntStream.range(0, request.getQuantity())
                    .forEach(i -> conn.getUserService().addBooster(conn.getUserId(), request.getData()));
            conn.getUserService().setGoldForUserId(conn.getUserId(), conn.getUserService().getGoldForUserId(conn.getUserId()) - (PACK_COST * request.getQuantity()));
            response = Protocol.PurchaseWithGoldResponse.newBuilder()
                    .setResult(Protocol.PurchaseWithGoldResponse.PurchaseResult.PR_SUCCESS)
                    .build();
        }

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