package ai.pai.lensman.main;

import android.os.AsyncTask;

import com.android.common.executors.ThreadExecutor;

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

import java.util.ArrayList;
import java.util.HashMap;

import ai.pai.lensman.base.BaseInteractor;
import ai.pai.lensman.utils.HttpPostTask;
import ai.pai.lensman.utils.UrlContainer;

/**
 * Created by chengzhenyu on 2016/8/14.
 */
public class FetchSessionIdsInteractor implements BaseInteractor {

    private HttpPostTask fetchSessionIdsTask;
    private String lensmanId;
    private int num;
    private InteractorListener<ArrayList<String>> listener;

    public FetchSessionIdsInteractor(String lensmanId, int num, InteractorListener<ArrayList<String>> listener){
        this.num = num;
        this.listener = listener;
        this.lensmanId = lensmanId;
    }

    @Override
    public void startJob() {
        cancelJob();
        HashMap<String,String> params = new HashMap<>();
        params.put("user_id",lensmanId);
        params.put("num",String.valueOf(num));
        fetchSessionIdsTask = new HttpPostTask(params){

            String message;
            ArrayList<String> sessionIds;
            @Override
            protected boolean parseResponse(String response) {
                try{
                    JSONObject json = new JSONObject(response);
                    int status = json.getInt("status");
                    if(status == 200){
                        JSONArray sessionArray = json.getJSONArray("data");
                        if(sessionArray!=null && sessionArray.length()>0){
                            sessionIds = new ArrayList<>();
                            for(int k = 0; k< sessionArray.length();k++){
                                sessionIds.add(sessionArray.getString(k));
                            }
                        }
                        return true;
                    }else{
                        message = json.getString("message");
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
                return false;
            }

            @Override
            protected void onPostFail() {
                super.onPostFail();
                listener.onInteractFail(message);
            }

            @Override
            protected void onPostSuccess() {
                super.onPostSuccess();
                listener.onInteractSuccess(sessionIds);
            }
        };
        fetchSessionIdsTask.executeOnExecutor(ThreadExecutor.getInstance().getExecutor(), UrlContainer.SESSION_IDS_CREATE);
    }

    @Override
    public void cancelJob() {
        if(fetchSessionIdsTask==null){
            return;
        }
        if(fetchSessionIdsTask.getStatus()== AsyncTask.Status.RUNNING){
            fetchSessionIdsTask.cancel(true);
        }
        fetchSessionIdsTask = null;
    }
}
