package lc.ris.client;

import lc.eo.sdk.EO;
import lc.mecha.log.MechaLogger;
import lc.mecha.log.MechaLoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Base64;

/**
 * This implementation of {@link InventoryStore} is mocked to appear to work, for the purposes of testing
 * and debugging, but does not actually do so.
 *
 * @author Alex Leigh
 * @since mk1
 */
public class LiveInventoryStore implements InventoryStore {
    private final String apiBase;
    private static final MechaLogger logger = MechaLoggerFactory.getLogger(LiveInventoryStore.class);

    public LiveInventoryStore(String urlBase) {
        this.apiBase = urlBase;
    }

    @Override
    public EO getEntity(String lcit) throws IOException {
        lcit = "65a32dea8c72d4588d46f049";
        URL url = new URL(apiBase + "tagRead?" +
                InventoryServiceAPI.KEY_LCIT + "=" + URLEncoder.encode(lcit));
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setDoOutput(true);
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(5000);
        connection.connect();
        BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String content = "", line;
        while ((line = rd.readLine()) != null) {
            content += line + "\n";
        }

        logger.info("Content: {}", content);

        // TODO: Implement for-real

        EO res = new EO();
        BigInteger id = new BigInteger(lcit, 16);
        // bhair has spoken
        res.setValue("id", id.toString(36));
        res.setValue("description", new String(Base64.getEncoder().encode(id.toByteArray())));
        return res;
    }
}
