package com.zoblak.farm;


import android.util.JsonReader;
import android.util.JsonToken;
import android.util.Log;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;


/**
 * Created by senadu on 11/14/16.
 */

public class ZoblakClient {
    private String controllers;

    public ZoblakClient(String controllers) {
        this.controllers = controllers;


    }

    public AlarmPingResponse PingServer() {
        HttpURLConnection urlConnection = null;
        AlarmPingResponse result = new AlarmPingResponse(controllers);

        URL url = null;
        try {
            url = new URL("http://agrar.zoblak.com/api/v1.0/alarm/" + controllers + "/phonePing");

            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setReadTimeout(10000);
            urlConnection.setConnectTimeout(15000);
            urlConnection.setRequestMethod("POST");
            urlConnection.setDoInput(true);
            urlConnection.setDoOutput(true);
            urlConnection.setRequestProperty("Content-Type", "application/json");

            OutputStream os = urlConnection.getOutputStream();
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));
            writer.write("{}");
            writer.flush();
            writer.close();
            os.close();

            urlConnection.connect();

            InputStream in = urlConnection.getInputStream();
            String jsonString = convertStreamToString(in);
            Log.e("JsonString", jsonString);
            JsonReader jr = new JsonReader(new StringReader(jsonString));
            result = readResponse(jr);

        } catch (MalformedURLException e) {
            Log.e("zoblakClient", "malformed: " + e.getLocalizedMessage());
        } catch (IOException e) {
            Log.e("zoblakClient", "ioexception: " + e.getLocalizedMessage());
            result.setAlarmTriggered(false);
            result.setServerError(false);
        }

        if (urlConnection != null) urlConnection.disconnect();

        return result; // if no response then
    }

    private AlarmPingResponse readResponse(JsonReader reader) {
        AlarmPingResponse result = new AlarmPingResponse(controllers);


        try {
            reader.beginObject();
            while (reader.hasNext()) {
                String name = reader.nextName();
                if (name.equals("alarmTriggered")  && reader.peek() != JsonToken.NULL) {
                    result.setAlarmTriggered(reader.nextBoolean());
                } else if (name.equals("tooHot")  && reader.peek() != JsonToken.NULL) {
                    result.setTooHot(reader.nextBoolean());
                } else if (name.equals("tooCold")  && reader.peek() != JsonToken.NULL) {
                    result.setTooCold(reader.nextBoolean());
                } else if (name.equals("boxSilent")  && reader.peek() != JsonToken.NULL) {
                    result.setBoxSilent(reader.nextBoolean());
                } else {
                    reader.skipValue();
                }
            }
        } catch (IOException e) {
            Log.e("zoblakClient", "reading result: " + e.getLocalizedMessage());
        }

        return result;


    }


    private static String convertStreamToString(InputStream is) {

        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

}
