package com.yyrh.utils;

import android.text.TextUtils;

import com.yyrh.core.entity.Session;
import com.yyrh.core.network.Host;

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

import java.util.ArrayList;

import cn.yyxx.support.JsonUtils;

/**
 * @author #Suyghur.
 * Created on 2021/10/20
 */
public class SessionUtils {

    private SessionUtils() {

    }

    private static final class SessionUtilsHolder {
        private static final SessionUtils INSTANCE = new SessionUtils();
    }

    public static SessionUtils getInstance() {
        return SessionUtilsHolder.INSTANCE;
    }

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

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

        try {
            jsonObject.put("info", jsonArray);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String model = "online";
        if (Host.MODEL == 0) {
            model = "test";
        }
        MMKVUtils.getInstance().userKV.encode(model, jsonObject.toString());
    }

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

    }

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

    /**
     * {"info":{"abc123":{"uid":"abc123","username":"","userpwd":"","token":"","auto_login":1}}}
     */
    public ArrayList<Session> getLocalSession() {
        String model = "online";
        if (Host.MODEL == 0) {
            model = "test";
        }
        String json = MMKVUtils.getInstance().userKV.decodeString(model, "");
        return toList(json);
    }

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

        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject = new JSONObject();
        for (Session session : userLists) {
            YYLog.d(session.toString());
            jsonArray.put(session.toJsonObject());
        }

        try {
            jsonObject.put("info", jsonArray);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        YYLog.d("写入用户信息：" + jsonObject.toString());
        String model = "online";
        if (Host.MODEL == 0) {
            model = "test";
        }
        MMKVUtils.getInstance().userKV.encode(model, jsonObject.toString());
    }

    private static ArrayList<Session> toList(String json) {
        if (TextUtils.isEmpty(json)) {
            return null;
        }
        YYLog.d("文件读出来：" + json);
        ArrayList<Session> 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++) {
                Session session = new Session();
                JSONObject obj = infoObject.getJSONObject(i);
                if (JsonUtils.hasJsonKey(obj, "user_id")) {
                    session.userId = obj.getString("user_id");
                }
                if (JsonUtils.hasJsonKey(obj, "user_name")) {
                    session.userName = obj.getString("user_name");
                }
                if (JsonUtils.hasJsonKey(obj, "pwd")) {
                    session.pwd = obj.getString("pwd");
                }

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

}
