package org.algorithm.core.cnn.model.impl;

import org.algorithm.core.cnn.AlgorithmCNNExecutor;
import org.algorithm.core.cnn.entity.Lemma;
import org.algorithm.core.cnn.entity.Triad;
import org.algorithm.util.HttpGetAndPost;
import org.diagbot.pub.utils.PropertiesUtil;
import org.springframework.util.StringUtils;

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

/**
 * @Author: bijl
 * @Date: 2019/5/21 11:02
 * @Decription: 关系抽取模型接口，从网络中获取
 */
public class RelationExtractionModelFromHttp extends AlgorithmCNNExecutor {
    private final int MAX_LEN = 512;
    @Override
    public List<Triad> execute(String content, List<Triad> triads) {
        String url = getUrl();
        // 句子长度不超过MAX_LEN，实体数超过两个
        if (content.length() > this.MAX_LEN || triads.size() < 1) {
            return new ArrayList<>();
        }
        String positions = makePositionsParam(triads);
        String indexPairAndRelations = HttpGetAndPost.sendPost(url,
                "sentence="+content+"&positions="+positions);
        // 模型服务异常统一标识：ModelServiceError
        if ("ModelServiceError".equals(indexPairAndRelations)){
            System.err.println("Error happen in Model service.");
            return new ArrayList<>();
        }
        // 合并信息到三元组中
        return mergePredictInfoToTriads(indexPairAndRelations, triads);
    }

    /**
     * 用lemma内部属性position组成字符串，按lemma在lemmas中的顺序
     * @param triads 实体list
     * @return
     */
    private String makePositionsParam(List<Triad> triads){
        String results = "";
        for(Triad triad: triads)
            results += triad.getL_1().getPosition() +  "^" + triad.getL_2().getPosition() + "|";  // 形式：1,2|33,45|
        if (!StringUtils.isEmpty(results)) {
            results = results.substring(0, results.length() - 1);  // 形式：1,2|33,45
        }
        return results;
    }

    /**
     * 获取url
     * @return
     */
    private String getUrl(){
        PropertiesUtil prop = new PropertiesUtil("/algorithm.properties");
        return prop.getProperty("relationExtractionUrl");
    }

    /**
     * 合并预测信息到三元组中去
     * @param indexPairAndRelations 预测信息，来自网络 // 形式：1,2:有|3,5:无
     * @param triads 实体
     * @return 有关系的实体对
     */
    private List<Triad> mergePredictInfoToTriads(String indexPairAndRelations, List<Triad> triads){
        List<Triad> result = new ArrayList<>();
        String[] posRelationArray = indexPairAndRelations.split("\\|");
        for (int i = 0; i< triads.size(); i++) {
            if ("1".equals(posRelationArray[i])) {
                result.add(triads.get(i));
            }
        }
//        String[] info;
//        String[] indexPair;
//        int index1;
//        int index2;
//        for(String posRelation:posRelationArray){
//            info = posRelation.split(":");  // 形式：1,2:有
//            if ("有".equals(info[1])){  // 仅返回有关系的
//                indexPair = info[0].split(","); // 形式：1,2
//                index1 = Integer.parseInt(indexPair[0]);
//                index2 = Integer.parseInt(indexPair[1]);
//                Triad triad = new Triad();
//                triad.setL_1(lemmas.get(index1));
//                triad.setL_2(lemmas.get(index2));
//                triad.setRelation(info[1]);
//                triads.add(triad);
//            }
//        }

        return result;
    }
}

