package cn.hmsoft.ai.face.baidu;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import com.baidu.aip.util.Base64Util;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import cn.hmsoft.ai.baidu.BaiduTokenService;
import cn.hmsoft.ai.face.FaceSearch;
import cn.hmsoft.application.SpringHelper;
import cn.hmsoft.helper.FileHelper;
import cn.hmsoft.helper.http.HttpHelper;

public class BaiduPhotoSearchAI extends FaceSearch {
	private final static String url = "https://aip.baidubce.com/rest/2.0/face/v3/search";

	@Override
	public String searchFace(File file, String groupIds) {
		Map<String, Object> options = new HashMap<String, Object>();
		try {
			options.put("image", Base64Util.encode(FileHelper.readFileByBytes(file.getPath())));

			options.put("image_type", "BASE64");
			options.put("match_threshold", "50");
			options.put("liveness_control", "NORMAL");
			options.put("quality_control", "LOW");
			options.put("group_id_list", groupIds);

			String param = new GsonBuilder().create().toJson(options);

			String result = HttpHelper.post(url(), "application/json", param);
			// System.out.println(result);
			JsonObject json = new JsonParser().parse(result).getAsJsonObject();

			int error_code = json.get("error_code").getAsInt();
			if (error_code == 0) {
				JsonObject r =json.get("result").getAsJsonObject();
				JsonObject p = r.getAsJsonArray("user_list").get(0).getAsJsonObject();
				return p.get("user_id").getAsString();
			}else {
				
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	private String url() {
		return url + "?access_token=" + SpringHelper.getBean(BaiduTokenService.class).getBaiduToken();
	}
}