package com.ch.jedge.jbot.knbase.intent;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ch.jedge.jbot.agent.JedgeGdeSession;
import com.ch.jedge.jbot.knbase.JedgeGptApp;

import java.util.ArrayList;
import java.util.List;

/**
 *
 */
public class JedgeGdeQuery {
    private final JedgeGptApp mGdeApp;
    private final JedgeGdeSession mGdeSession;

    public final String query_;

    public JSONArray words_;

    public List<JSONArray> term_words_;

    //提示词中提取的关键字:
    public final List<String> sel_words_ = new ArrayList<>();

    //对子意图的支持：(如果存在多语句)

    public JedgeGdeQuery(JedgeGptApp app, JedgeGdeSession gds, String query) {
        mGdeApp = app;
        mGdeSession = gds;
        query_= query;
    }

    //对句子进行模式化分解
    public void pushWords(JSONArray words) {
        words_ = words;
        //n-gram算法解析

    }

    //根据匹配到的短语重组词汇
    public void rebuildWords(int start, int end, List<JSONObject> terms) {
        if(term_words_==null)
            term_words_ = new ArrayList<>();
        //提取每个短语，且相互不覆盖时
        //歧义短语划分的多语义路径的处理
        JSONArray new_words_ = new JSONArray();
        JSONObject[] oo = new JSONObject[end-start];
        for(JSONObject t : terms) {
            int ts = t.getInteger("s") - start;
            int te = t.getInteger("l") + ts;

            //检查词是否已被占用
            for(int i=ts;i<te;i++) {
                if(oo[i]!=null) {
                    break;
                }
                oo[i] = t;  //标记短语对象
            }
        }

        //词与短语混合拼装
        for(int i=0;i<oo.length;) {
            if(oo[i]==null) {
                new_words_.add(words_.get(i));
                i++;
            } else {
                JSONObject w = oo[i];
                int ol = w.getInteger("l");
                w.remove("s");
                w.remove("l");
                new_words_.add(w);
                i+=ol;
            }
        }
        term_words_.add(new_words_);
    }

    public void rebuildWords(int start, int end, boolean isMulti) {
        if(term_words_==null)
            term_words_ = new ArrayList<>();
        if(!isMulti) {
            term_words_.add(words_);
            return;
        }

        JSONArray new_words_ = new JSONArray();
        //词与短语混合拼装
        for(int i=start;i<end;) {
            new_words_.add(words_.get(i));
            i++;
        }
        term_words_.add(new_words_);
    }

}
