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 ForecastFetcherLivedoor {
    final public static String BASE_URL = "http://weather.livedoor.com/forecast/webservice/json/v1?city=";
    public String areaId;
    public Context context;

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

    public boolean save(ConfigManager config) {
        JsonObject json = getJson();
        if (json == null) return false;

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

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

            String label = day.getAsJsonPrimitive("telop").getAsString();
            StringBuffer ident = new StringBuffer();
            for (String part: label.split("のち|後|時々|ときどき", 2)) {
                if (part.equals("はれ") || part.equals("晴れ") || part.equals("晴")) {
                    if (reportedAt != null && reportedAt.getHours() > 16 && index == 1) {
                        ident.append(Theme.W_CLEAR_N);
                    } else {
                        ident.append(Theme.W_CLEAR_D);
                    }
                } else if (part.equals("雨") || part.equals("あめ")) {
                    ident.append(Theme.W_RAIN);
                } else if (part.equals("雪") || part.equals("ゆき")) {
                    ident.append(Theme.W_SNOW);
                } else if (part.equals("曇") || part.equals("曇り") || part.equals("くもり")) {
                    ident.append(Theme.W_CLOUD);
                }
            }

            Integer temp_max = null;
            Integer temp_min = null;
            try {
                JsonObject temp = day.getAsJsonObject("temperature");
                try {
                    JsonObject max = temp.getAsJsonObject("max");
                    temp_max = max.getAsJsonPrimitive("celsius").getAsInt();
                } catch (ClassCastException e) {
                    // ignroe
                }
                try {
                    JsonObject min = temp.getAsJsonObject("min");
                    temp_min = min.getAsJsonPrimitive("celsius").getAsInt();
                } catch (ClassCastException e) {
                    // ignore
                }
            } catch (ClassCastException e) {
                // ignore
            }

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

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

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

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

}
