package com.ch.jedge.jbot.dict;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ch.jedge.jbot.knbase.JedgeGptDomain;
import com.changhong.qlib.util.file.FileUtils;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 *  词库:
 *      动态加载,可从知识切片、领域或通用预置词库中加载
 */
public class JedgeWordDict {
    private final String name_;

    public String dictPath;

    public int ttl;     //对话一旦进入非专业领域后，在一定时间内自动清理。

    protected final Map<String, JedgeWordItem> wordItems = new HashMap<>();

    public JedgeWordDict(String path) {
        this.dictPath = path;
        this.name_ = FileUtils.getFilenameWithoutExt(path);
    }

    public JedgeWordDict(JedgeGptDomain domain) {
        this.dictPath = domain.getFilePath();
        this.name_ = domain.getDomainName();
    }

    public void appendWordItem(JedgeWordItem jedgeWordItem) {
        synchronized (wordItems) {
            JedgeWordItem old = wordItems.get(jedgeWordItem.word);
            if(old!=null) {
                old.freq += jedgeWordItem.freq;
                old.isGated = old.isGated || jedgeWordItem.isGated;
            } else
                wordItems.put(jedgeWordItem.word, jedgeWordItem);   //覆盖前面的重复词汇
        }
    }

    public String getName() {
        return name_;
    }

    public boolean isEmpty() {
        synchronized (wordItems) {
            return wordItems.isEmpty();
        }
    }

    public JSONArray getWordItemsInJson(boolean gated) {
        JSONArray re = new JSONArray();
        synchronized (wordItems) {
            for (JedgeWordItem entry : wordItems.values()) {
                if(gated!=entry.isGated) continue;
                JSONObject obj = new JSONObject();
                obj.put("w", entry.word);
                obj.put("t", entry.type);
                obj.put("f", entry.freq);
                re.add(obj);
            }
        }
        return re;
    }

    public Collection<JedgeWordItem> getWordItems() {
        synchronized (wordItems) {
            return wordItems.values();
        }
    }

    public JedgeWordItem getWordItem(String word) {
        synchronized (wordItems) {
            return wordItems.get(word);
        }
    }
}
