package ai.pai.lensman.login;

import android.os.AsyncTask;

import com.android.common.executors.ThreadExecutor;
import com.android.common.utils.LogHelper;

import org.json.JSONObject;

import java.util.HashMap;

import ai.pai.lensman.base.BaseInteractor;
import ai.pai.lensman.db.Preferences;
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 HttpPostTask fetchTokenTask;
    private HttpPostTask fetchUserInfoTask;
    private InteractorListener<String> listener;
    private static final String APP_ID = "wxf4832536d9dda70a";
    private static final String APP_SECRET = "9a2efcae3c6038b5450b0c2ef3187b1f";
    private String wxCode;

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

    @Override
    public void startJob() {
        fetchToken();
    }

    @Override
    public void cancelJob() {
        cancelJob(loginTask);
        cancelJob(fetchTokenTask);
        cancelJob(fetchUserInfoTask);
    }

    private void cancelJob(HttpPostTask task) {
        if (task == null) {
            return;
        }
        if (task.getStatus() == AsyncTask.Status.RUNNING) {
            task.cancel(true);
        }
    }

    private void fetchToken() {

        final String tokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + APP_ID
                + "&secret=" + APP_SECRET + "&code=" + wxCode + "&grant_type=authorization_code";
        LogHelper.d("czy","interactor fetchToken with url = "+tokenUrl);
        fetchTokenTask = new HttpPostTask(null) {

            String token;
            String openId;

            @Override
            protected boolean parseResponse(String response) {
                LogHelper.d("czy","interactor fetchToken parseResponse response = "+response);
                try {
                    JSONObject json = new JSONObject(response);
                    token = json.getString("access_token");
                    openId = json.getString("openid");
                    return true;
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return false;
            }

            @Override
            protected void onPostSuccess() {
                super.onPostSuccess();
                fetchUserInfo(token, openId);
            }

            @Override
            protected void onPostFail() {
                super.onPostFail();
            }
        };
        fetchTokenTask.executeOnExecutor(ThreadExecutor.getInstance().getExecutor(), tokenUrl);
    }

    private void fetchUserInfo(String token, String openId) {

        String userInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + token + "&openid=" + openId;
        LogHelper.d("czy","interactor fetchUserInfo with url = "+userInfoUrl);
        fetchUserInfoTask = new HttpPostTask(null) {
            HashMap<String, String> params;

            @Override
            protected boolean parseResponse(String response) {
                LogHelper.d("czy","interactor fetchUserInfo parseResponse response = "+response);
                try {
                    JSONObject json = new JSONObject(response);
                    params = new HashMap<>();
                    params.put("unionid", json.getString("unionid"));
                    params.put("openid", json.getString("openid"));
                    params.put("sex", json.getString("sex"));
                    params.put("nickname", json.getString("nickname"));
                    params.put("headimgurl", json.getString("headimgurl"));
                    params.put("country", json.getString("country"));
                    params.put("province", json.getString("province"));
                    params.put("city", json.getString("city"));
                    return true;
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return false;
            }

            @Override
            protected void onPostSuccess() {
                super.onPostSuccess();
                wxLogin(params);
            }

            @Override
            protected void onPostFail() {
                super.onPostFail();
            }
        };
        fetchUserInfoTask.executeOnExecutor(ThreadExecutor.getInstance().getExecutor(), userInfoUrl);
    }

    private void login() {
        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);
    }

    private void wxLogin(HashMap<String, String> params) {

        loginTask = new HttpPostTask(params) {

            String lensmanId;
            String userName;
            String message;

            @Override
            protected boolean parseResponse(String response) {
                LogHelper.d("czy","interactor wxLogin parseResponse response = "+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");
                        userName = info.getString("nickname");
                        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);
                Preferences.getInstance().setLensManId(lensmanId);
                Preferences.getInstance().setUserName(userName);
            }
        };
        loginTask.executeOnExecutor(ThreadExecutor.getInstance().getExecutor(), UrlContainer.WX_LOGIN_URL);
    }

}
