/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.actionbazaar.interfaces.socket;

import com.actionbazaar.domain.Bid;
import java.io.StringReader;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonReader;
import javax.websocket.DecodeException;
import javax.websocket.Decoder;
import javax.websocket.EncodeException;
import javax.websocket.Encoder;
import javax.websocket.EndpointConfig;

/**
 * This class handles encoding and decoding a BidEvent to and from JSON
 * form using the javax.json.* API (JSR-353).
 * 
 */
public class BidEventEncoderDecoder implements Encoder.Text<BidEvent>, Decoder.Text<BidEvent> {
    
    private static final Logger logger = Logger.getLogger(BidEventEncoderDecoder.class.getName());
    
    public BidEventEncoderDecoder() {
    }

    /**
     * Create a JSON representation of the given BidEvent object.
     * 
     * @param bidEvent
     * @return
     * @throws EncodeException 
     */
    @Override
    public String encode(BidEvent bidEvent) throws EncodeException {
        logger.log(Level.FINE, "encode {0}", bidEvent.toString());
        Bid bid = bidEvent.getBid();
        JsonObject jsonBidEvent = Json.createObjectBuilder()
                .add("type", bidEvent.getType())
                .add("id", bid.getId())
                .add("bidder", bid.getBidder())
                .add("item", bid.getItem())
                .add("amount", String.format("%.2f", bid.getAmount()))
                .build();

        logger.log(Level.INFO,
                "encode {0}",
                new Object[]{jsonBidEvent.toString()
                });
        return jsonBidEvent.toString();

    }

    /**
     * Create a BidEvent object from the given JSON payload.
     * 
     * @param jsonBidEvent
     * @return
     * @throws DecodeException 
     */
    @Override
    public BidEvent decode(String jsonBidEvent) throws DecodeException {
        logger.log(Level.FINE, "decode from {0}", jsonBidEvent);

        JsonReader jsonReader = Json.createReader(new StringReader(jsonBidEvent));
        JsonObject json = jsonReader.readObject();

        Bid bid = new Bid();

        bid.setAmount(Double.valueOf(json.getString("amount")));
        bid.setBidder(json.getString("bidder"));
        bid.setItem(json.getString("item"));
        bid.setId(Long.valueOf(json.getInt("id")));

        BidEvent bidEvent = new BidEvent(bid);
        bidEvent.setType(json.getString("type"));

        return bidEvent;
    }

    @Override
    public boolean willDecode(String string
    ) {
        return true;
    }

    @Override
    public void init(EndpointConfig ec) {
        // NOOP
    }

    @Override
    public void destroy() {
        // NOOP
    }

}
