package com.diaoyun.zion.master.util;

import com.diaoyun.zion.master.bo.TencentTranslateParam;
import com.diaoyun.zion.master.bo.TencentWordsegParam;
import com.diaoyun.zion.master.thread.TaskLimitSemaphore;
import com.diaoyun.zion.master.thread.TranslateCallable;
import com.diaoyun.zion.master.thread.WordposCallable;
import net.sf.json.JSONArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * 分词
 */
public class WordposHelper {
    private static Logger logger = LoggerFactory.getLogger(WordposHelper.class);
    //默认10条线程跑分词
    private static final TaskLimitSemaphore taskLimitSemaphore=new TaskLimitSemaphore(10);

    /**
     * 翻译文本
     * @param valeMap
     * @param text
     * @throws ExecutionException
     * @throws InterruptedException
     */
    public static void separeteText(List<Map<String, Object>> futureList, Map<String,Object> valeMap, String text) {
        TencentWordsegParam param=new TencentWordsegParam(text);
        Future<Map<String,Object>> future = null;
        try {
            future = taskLimitSemaphore.submit(new WordposCallable(param));
            Map<String,Object> map=new HashMap<>();
            map.put("future",future);
            map.put("value",valeMap);
            futureList.add(map);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
    }

    /**
     * 等待翻译结果
     * @param futureList
     */
    public static void waitForResult(List<Map<String, Object>> futureList) throws ExecutionException, InterruptedException, TimeoutException {
        for(Map<String,Object> futureMap:futureList) {
            Future<Map<String,Object>> future= (Future<Map<String, Object>>) futureMap.get("future");
            Map<String,Object> valeMap = (Map<String,Object> ) futureMap.get("value");
            while(!future.isDone());//Future返回如果没有完成，则一直循环等待，直到Future返回完成
            Map<String,Object> resultMap=future.get(10000, TimeUnit.MILLISECONDS);
            if(resultMap!=null&&(int)resultMap.get("ret")==0) {
                Map<String,Object> dataMap=(Map<String,Object>)resultMap.get("data");
                JSONArray tokens = (JSONArray) dataMap.get("mix_tokens");//base_tokens
                valeMap.put("base_tokens",tokens);
                //logger.info(tokens.toString());
            } else {
                logger.error("翻译出错");
            }
        }
    }

}
