package cn.yyxx.commsdk.impl.merge.user;

import android.text.TextUtils;

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

import java.util.ArrayList;

import cn.yyxx.commsdk.base.utils.Logger;
import cn.yyxx.commsdk.core.utils.MMKVUtils;
import cn.yyxx.support.JsonUtils;

public class UserSessionManager {

    private static volatile UserSessionManager mInstance;


    String model = "online";

    private UserSessionManager() {

    }

    public static UserSessionManager getInstance() {
        if (null == mInstance) {
            synchronized (UserSessionManager.class) {
                if (null == mInstance) {
                    mInstance = new UserSessionManager();
                }
            }
        }
        return mInstance;
    }


    private static ArrayList<UserSession> toList(String json) {
        if (TextUtils.isEmpty(json)) {
            return null;
        }

        ArrayList<UserSession> infoList = null;
        try {
            JSONObject jsonObject = new JSONObject(json);
            infoList = new ArrayList<>();
            if (!JsonUtils.hasJsonKey(jsonObject, "info")) {
                return null;
            }
            JSONArray infoObject = jsonObject.getJSONArray("info");
            for (int i = 0; i < infoObject.length(); i++) {
                UserSession userSession = new UserSession();
                JSONObject obj = infoObject.getJSONObject(i);
                if (JsonUtils.hasJsonKey(obj, "uname")) {
                    userSession.uname = obj.getString("uname");
                }
                if (JsonUtils.hasJsonKey(obj, "password")) {
                    userSession.password = obj.getString("password");
                }
                if (JsonUtils.hasJsonKey(obj, "login_token")) {
                    userSession.login_token = obj.getString("login_token");
                }

                infoList.add(userSession);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return infoList;
    }



    public synchronized void saveSession(UserSession userSession) {
        if (userSession == null) {
            return;
        }
        ArrayList<UserSession> userList = getLocalSession();
        if (null == userList) {
            userList = new ArrayList<>();
        }
        if (userList.size() > 0) {
            boolean isSessionExist = false;
            for (int i = 0; i < userList.size(); i++) {
                //TODO 当前登录用户已经存在用户列表里，更新用户数据(移除旧的，在0的位置插入)
                UserSession session = userList.get(i);
                if (userSession.uname.equals(session.uname)) {
                    isSessionExist = true;
                    //移除
                    userList.remove(session);
                    userList.add(0, userSession);
                    break;
                }
            }
            if (!isSessionExist) {
                //TODO 当前登录用户不存在用户列表里，在0的位置插入
                userList.add(0, userSession);
            }
        } else {
            userList.add(userSession);
        }

        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject = new JSONObject();
        for (UserSession session : userList) {
            jsonArray.put(session.toJSONObject());
        }

        try {
            jsonObject.put("info", jsonArray);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        MMKVUtils.getInstance().userKV.encode(model, jsonObject.toString());
    }





    public UserSession getLocalLastSession() {
        ArrayList<UserSession> list = getLocalSession();
        if (null == list) {
            return null;
        }
        UserSession session = list.get(0);
        Logger.d("最后登陆的用户信息:" + session.toString());
        return session;

    }


    public ArrayList<UserSession> getLocalSessionLimit3() {
        ArrayList<UserSession> list = getLocalSession();
        if (null == list) {
            return null;
        }
        if (list.size() <= 3) {
            return list;
        } else {
            ArrayList<UserSession> temp = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                UserSession session = list.get(i);
                temp.add(session);
                if (temp.size() == 3) {
                    break;
                }
            }
            return temp;
        }
    }


    public ArrayList<UserSession> getLocalSession() {
        String json = MMKVUtils.getInstance().userKV.decodeString(model, "");
        return toList(json);
    }

    /**
     * 删除用户信息
     *
     * @param uname
     */
    public synchronized void removeSession(String uname) {
        ArrayList<UserSession> userLists = getLocalSession();
        if (userLists == null || userLists.size() == 0) {
            return;
        }
        UserSession deleteUser = null;
        for (UserSession session : userLists) {
            if (session.uname.equals(uname)) {
                deleteUser = session;
                break;
            }
        }
        if (deleteUser != null) {
            userLists.remove(deleteUser);
        }

        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject = new JSONObject();
        for (UserSession session : userLists) {
            Logger.d(session.toString());
            jsonArray.put(session.toJSONObject());
        }

        try {
            jsonObject.put("info", jsonArray);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        MMKVUtils.getInstance().userKV.encode(model, jsonObject.toString());
    }

}
