package com.gingersoft.gsa.cloud.function;

import com.gingersoft.gsa.cloud.account.user.info.UserInfo;
import com.gingersoft.gsa.cloud.account.user.state.LogoutState;
import com.gingersoft.gsa.cloud.account.user.state.UserState;
import com.gingersoft.gsa.cloud.database.bean.Function;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author : bin
 * @create date: 2020-11-23
 * @update date: 2020-11-23
 * @description:
 */
public class XFunctionManager implements XFunctionAction {

    private static XFunctionManager sXFunctionManager = null;

    /**
     * 所有功能數據
     */
    private HashMap<String, Function> mFunctionMap = new HashMap<>();

    private XFunctionManager() {
    }

    public static XFunctionManager newInstance() {
        if (sXFunctionManager == null) {
            sXFunctionManager = new XFunctionManager();
        }
        return sXFunctionManager;
    }

    @Override
    public List<Function> getFunctionItems(String targetResKey) {
        List<Function> functions = new ArrayList<>();
        if (mFunctionMap.size() == 0) {
            return functions;
        }
        Iterator entries = mFunctionMap.entrySet().iterator();
        while (entries.hasNext()) {
            Map.Entry entry = (Map.Entry) entries.next();
            String resUrl = (String) entry.getKey();
            //獲取具體的功能組，如table/bottom/init下的table/bottom組
            String[] keyRes = resUrl.split("/");
            if (keyRes.length > 1) {
                resUrl = resUrl.substring(0, keyRes[keyRes.length - 1].length());
                if(resUrl.equals(targetResKey)){
                    /**
                     * 匹配功能組成功{@link XFunctionItems}
                     */
                    Function item = (Function) entry.getValue();
                    functions.add(item) ;
                }
            }
        }
        return functions;
    }

    @Override
    public Function getFunctionItem(String targetResKey) {
        if (mFunctionMap.size() == 0) {
            return null;
        }
        Iterator entries = mFunctionMap.entrySet().iterator();
        while (entries.hasNext()) {
            Map.Entry entry = (Map.Entry) entries.next();
            String resUrl = (String) entry.getKey();
            if (targetResKey.equals(resUrl)) {
                /**
                 * 匹配單個功能成功{@link XFunctionItem}
                 */
                Function item = (Function) entry.getValue();
                return item;
            }
        }
        return null;
    }

    @Override
    public void updateFunctions(List<Function> functions) {
        if (functions == null) {
            return;
        }
        if (mFunctionMap.size() > 0) {
            mFunctionMap.clear();
        }
        for (Function function : functions) {
            mFunctionMap.put(function.getResUrl(), function);
        }
    }

}
