package godau.fynn.dsbdirect;

import android.app.Activity;
import android.app.AlertDialog;
import godau.fynn.dsbdirect.manager.DownloadManager;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.Locale;

public class NewsQuery implements Runnable {

    /*
     * News structure:
     * {
     *  "statusMessage": "Message for the user",
     *  "statusMessageDE": "Nachricht an Nutzer",
     *  "queryBodyBaseJson": "optional: das neue queryBodyBaseJson",
     *  "querySendDate": boolean, optional
     * }
     */

    Activity context;
    DownloadManager downloadManager;
    Utility u;

    public NewsQuery(Activity context, DownloadManager downloadManager) {
        this.context = context;
        this.downloadManager = downloadManager;
        u = new Utility(context);
    }

    @Override
    public void run() {
        try {
            JSONObject news = downloadManager.downloadNews();

            // Get message from news

            String message;

            // German or not german (hardcoded and uncool)
            if (Locale.getDefault().toString().contains("de")) {
                message = news.getString("statusMessageDE");
            } else {
                message = news.getString("statusMessage");
            }

            // Get new query body base json
            if (news.has("queryBodyBaseJson")) {
                u.getSharedPreferences()
                        .edit()
                        .putString("queryBodyBaseJson", news.getString("queryBodyBaseJson"))
                        .apply();
            }

            // Get new date bool
            if (news.has("querySendDate")) {
                u.getSharedPreferences()
                        .edit()
                        .putBoolean("querySendDate", news.getBoolean("querySendDate"))
                        .apply();
            }


            // Show news
            popup(message);

        } catch (JSONException | DownloadManager.UnexpectedResponseException ex) {
            popup(context.getString(R.string.news_network_invalid_response));
            ex.printStackTrace();
        } catch (IOException ex) {
            popup(context.getString(R.string.news_network_error_generic));
            ex.printStackTrace();
        }
    }

    private void popup(final String message) {
        context.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                new AlertDialog.Builder(context)
                        .setMessage(message)
                        .show();
            }
        });

    }
}
