package cloud.hmml.mmw;

import android.content.Context;
import android.util.Log;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.koushikdutta.ion.Ion;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.ExecutionException;


public class ForecastFetcher {
    final public static String BASE_URL = "https://mmw.hmml.cloud/api/v1/forecasts/";
    public String areaId;
    public String areaNs;
    public Context context;

    public ForecastFetcher(Context context, String areaNs, String areaId) {
        this.areaNs = areaNs;
        this.areaId = areaId;
        this.context = context;
    }

    public boolean save(ConfigManager config) {
        JsonObject json = getJson();
        if (json == null) {
            Log.e("forecast-fetcher", "Failed to fetch forecast JSON.");
            return false;
        }

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
        Date reportedAt = null;
        Calendar reportedAtCal = null;
        try {
            reportedAt = df.parse(json.getAsJsonPrimitive("reported_at").getAsString());
            config.saveReportedAt(reportedAt);
        } catch (ParseException e) {
            Log.e("forecast-fetcher", "Failed to parse reported_at!");
            e.printStackTrace();
        } catch (NullPointerException e) {
            // ignore!
        }

        int index = 1;
        for (JsonElement j: json.getAsJsonArray("daily_forecasts")) {
            JsonObject day = j.getAsJsonObject();

            String label = day.getAsJsonPrimitive("weather_label").getAsString();
            String ident = day.getAsJsonPrimitive("weather_symbol").getAsString();
            Integer temp_max = null;
            Integer temp_min = null;
            Integer pop = null;
            try {
                temp_max = day.getAsJsonPrimitive("temp_max").getAsInt();
            } catch (ClassCastException e) {
                // ignroe
            }
            try {
                temp_min = day.getAsJsonPrimitive("temp_min").getAsInt();
            } catch (ClassCastException e) {
                // ignroe
            }
            try {
                pop = day.getAsJsonPrimitive("pop").getAsInt();
            } catch (ClassCastException e) {
                // ignroe
            }

            config.saveWeather(index, ident, label, temp_min, temp_max, pop);

            index++;
            if (index > 2) break;
        }

        config.saveUpdatedAt();
        Log.d("forecast-fetcher", "Forecast has been fetched successfully.");
        return true;
    }

    private JsonObject getJson() {
        try {
            return Ion.with(this.context)
                    .load(BASE_URL + areaNs + "/" + areaId + ".json")
                    .setHeader("X-Requested-With", "Android cloud.hmml.mmw")
                    .asJsonObject().get();
        } catch (InterruptedException e) {
            Log.e("forecast-fetcher", "Exception in fetching json: " + e.getMessage());
            e.printStackTrace();
            return null;
        } catch (ExecutionException e) {
            Log.e("forecast-fetcher", "ExecutionException in fetching json: "+e.getMessage());
            e.printStackTrace();
            return null;
        }
    }
}
