package com.tomastc.smartwatchclient.lib.common;

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

import com.tomastc.smartwatchclient.R;
import com.tomastc.smartwatchclient.lib.ActionListenerCallback;
import com.tomastc.smartwatchclient.lib.SimpleSpinObject;
import com.tomastc.smartwatchclient.lib.SpinAdapter;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Arrays;

public abstract class AsyncGetSpinner {

    public SimpleSpinObject[] getSpinObject(Context context, String url, Spinner spinner, SimpleSpinObject defaultObj) {
        return getSpinObject(context, url, spinner, defaultObj, "{'cmd':'search'}");
    }

    public SimpleSpinObject[] getSpinObject(Context context, String url, Spinner spinner
            , SimpleSpinObject defaultObj, String json) {

        final SimpleSpinObject[][] objs = new SimpleSpinObject[1][1];

        try {
            new AsyncHttpClient(context
                    ,url
                    , json
            ) {
                @Override
                public void onFinished(String response, int resp_code) {
                    Log.d(context.getString(R.string.tag), "response: " + response);
                    // update mapItems
                    try {
                        JSONArray jArray = new JSONArray(response);
                        Log.d(context.getString(R.string.tag), "response json length: " + jArray.length());
                        if (jArray.length() == 0)
                            return;

                        objs[0] = new SimpleSpinObject[jArray.length() + (defaultObj!=null ? 1 : 0)];
                        if (defaultObj != null)
                            objs[0][0] = defaultObj;
                        for (int i=0;i<jArray.length();i++) {
                            String id = jArray.getJSONObject(i).getString("id");
                            String name = jArray.getJSONObject(i).getString("name");

                            objs[0][i+(defaultObj!=null ? 1 : 0)] = new SimpleSpinObject(id, name);
                        }

                        Log.d(context.getString(R.string.tag), Arrays.deepToString(objs[0]));


                        spinner.setAdapter(new SpinAdapter(
                                context, R.layout.spinner_list, objs[0]));

                        onActionSuccess("");

                    } catch (JSONException e) {
                        e.printStackTrace();
                        onActionFailure(e);
                    }
                }
            }
                    .execute();
        } catch (Exception e) {
            e.printStackTrace();
            onActionFailure(e);
        }

        return objs[0];
    }

    public abstract void onActionSuccess(String successMessage);
    public abstract void onActionFailure(Throwable throwableError);
}
