package ai.pai.lensman.login;

import android.os.AsyncTask;

import com.android.common.executors.ThreadExecutor;

import org.json.JSONObject;

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/12.
 */
public class LoginInteractor implements BaseInteractor{

    private HttpPostTask loginTask;
    private InteractorListener<String> listener;

    public LoginInteractor(InteractorListener<String> listener){
        this.listener = listener;
    }

    @Override
    public void startJob() {
        cancelJob();
        HashMap<String,String> params = new HashMap<>();
        params.put("username","chengzhenyu");
        params.put("password","paiai");

        loginTask = new HttpPostTask(params){

            String lensmanId;
            String message;
            @Override
            protected boolean parseResponse(String response) {
                try{
                    JSONObject json = new JSONObject(response);
                    int status = json.getInt("status");
                    if(status == 200){
                        JSONObject info = json.getJSONObject("data");
                        lensmanId = info.getString("user_id");
                        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(lensmanId);
            }
        };
        loginTask.executeOnExecutor(ThreadExecutor.getInstance().getExecutor(), UrlContainer.LOGIN_URL);
    }

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

}
