package com.danding.yang800.Presenter;

import android.content.Context;
import android.content.SharedPreferences;

import com.danding.yang800.BaseActivity;
import com.danding.yang800.ChangeShopNameActivity;
import com.danding.yang800.General.HttpCallBack;
import com.danding.yang800.Util.ToastUtil;
import com.danding.yang800.Util.VolleyUtil;

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

import java.util.HashMap;

public class BaseActivityPresenter {
    private BaseActivity context;
    SharedPreferences sp;

    public BaseActivityPresenter(BaseActivity context) {
        sp = context.getSharedPreferences("variable", Context.MODE_PRIVATE);
        this.context = context;
    }

    public void keepLogin() {
        HashMap<String, String> map = new HashMap<String, String>();
        new VolleyUtil(context).request(context, "login.loginHold", false, map, new HttpCallBack() {
            @Override
            public void onSuccess(JSONObject json) {
                sp.edit().putBoolean("login", true).commit();
            }

            @Override
            public void onerrSuccess() {
                tokenLogin();
            }

            @Override
            public void onCatch() {

            }

            @Override
            public void onFail() {
            }
        });


    }

    public void tokenLogin() {
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("token", sp.getString("token", ""));
        map.put("epCode", sp.getString("epCode", ""));
        new VolleyUtil(context).request(context, "login.tokenLogin", false, map, new HttpCallBack() {
            @Override
            public void onSuccess(JSONObject json) {
                try {
                    JSONObject jsondata = json.getJSONObject("result");
                    JSONObject jsonUser = jsondata.getJSONObject("user");
                    int userId = jsonUser.getInt("userId");
                    sp.edit().putInt("userId", userId).commit();
                    String token = jsonUser.getString("token");
                    sp.edit().putString("token", token).commit();
                    JSONObject jsonStore = jsondata.getJSONObject("store");
                    String storeId = jsonStore.getString("id");
                    sp.edit().putString("storeId", storeId).commit();
                    sp.edit().putBoolean("login", true).commit();
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onerrSuccess() {

            }

            @Override
            public void onCatch() {

            }

            @Override
            public void onFail() {
            }
        });
    }

}
