package ai.pai.lensman.login;

import android.content.Context;
import android.text.TextUtils;

import com.android.common.utils.LogHelper;
import com.tencent.mm.sdk.modelmsg.SendAuth;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import ai.pai.lensman.base.BaseInteractor;
import ai.pai.lensman.db.Preferences;

/**
 * Created by chengzhenyu on 2016/8/11.
 */
public class LoginPresenter implements LoginContract.Presenter,BaseInteractor.InteractorListener<String> {

    private   IWXAPI api;
    private Context context;
    private LoginContract.View view;
    private LoginInteractor interactor;
    private static final String APP_ID = "wxf4832536d9dda70a";

    public LoginPresenter(Context context,LoginContract.View view){
        this.view = view;
        this.context = context;
        api = WXAPIFactory.createWXAPI(context, APP_ID, true);
        api.registerApp(APP_ID);
    }

    @Override
    public void login() {
        LogHelper.d("czy","presenter login");

        SendAuth.Req req = new SendAuth.Req();
        req.scope = "snsapi_userinfo";
        req.state = "paiai_for_lensman";
        api.sendReq(req);
    }

    @Override
    public void start() {
        String wxCode = Preferences.getInstance().getWXCode();
        LogHelper.d("czy","presenter start with wx code = "+wxCode);
        if(!TextUtils.isEmpty(wxCode)){
            view.showProgressView();
            interactor = new LoginInteractor(wxCode,this);
            interactor.startJob();
            Preferences.getInstance().setWXCode("");
        }
    }

    @Override
    public void stop() {
        if(interactor!=null){
            interactor.cancelJob();
        }
    }


    @Override
    public void onInteractSuccess(String result) {
        view.hideProgressView();
        Preferences.getInstance().setLensManId(result);
        view.jumpMain();
    }

    @Override
    public void onInteractFail(String errorMsg) {
        view.hideProgressView();
        view.showLoginHint(errorMsg);
    }

}
