package com.zd.face.service;

import com.arcsoft.face.FaceEngine;
import com.arcsoft.face.FaceFeature;
import com.arcsoft.face.FaceInfo;
import com.arcsoft.face.FaceSimilar;
import com.arcsoft.face.enums.ErrorInfo;
import com.arcsoft.face.toolkit.ImageInfo;
import com.zd.common.core.utils.Assert;
import com.zd.face.config.FaceProperties;
import com.zd.face.handle.FaceEngineFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import static com.arcsoft.face.toolkit.ImageFactory.getRGBData;

/**
 * @Author: zhoupan
 * @Date: 2021/10/12/14:30
 * @Description:
 */
@Service
public class FaceService {

    @Autowired
    FaceEngineFactory faceEngineFactory;

    @Autowired
    FaceProperties faceProperties;


    /**
     * 人脸检测
     * @param imageInfo 待检测的图片信息
     * @return
     */
    public List<FaceInfo>  faceDetect(ImageInfo imageInfo)
    {
        List<FaceInfo> faceInfoList = new ArrayList<FaceInfo>();
        int errorCode = faceEngineFactory.initFaceEngineImage().detectFaces(imageInfo.getImageData(), imageInfo.getWidth(), imageInfo.getHeight(), imageInfo.getImageFormat(), faceInfoList);
        Assert.isTrue(errorCode==ErrorInfo.MOK.getValue(),"人脸检测失败！");
        return faceInfoList;
    }



    /**
     * 人脸特征提取
     * @return
     */
    public FaceFeature faceFeature(ImageInfo imageInfo,List<FaceInfo> faceInfoList)
    {
        FaceFeature faceFeature = new FaceFeature();
        FaceEngine imageFaceEngine = null;
        int errorCode;
        try {
            imageFaceEngine = faceEngineFactory.initFaceEngineImage();
            errorCode = imageFaceEngine.extractFaceFeature(imageInfo.getImageData(), imageInfo.getWidth(), imageInfo.getHeight(), imageInfo.getImageFormat(), faceInfoList.get(0), faceFeature);
        } finally {
            if(imageFaceEngine!=null)
            {
                imageFaceEngine.unInit();
            }

        }

        Assert.isTrue(errorCode==ErrorInfo.MOK.getValue(),"人脸特征提取失败！");

        return faceFeature;
    }
    /**
     * 人脸对比
     * @return
     */
    public Boolean compore(FaceFeature targetFaceFeature,FaceFeature sourceFaceFeature)
    {

        FaceSimilar faceSimilar = new FaceSimilar();
        FaceEngine faceEngine = null;
        int errorCode = 0;
        try {
            faceEngine = faceEngineFactory.initFaceEngineImage();
            errorCode = faceEngine.compareFaceFeature(targetFaceFeature, sourceFaceFeature, faceSimilar);
        } finally {
            if(faceEngine!=null)
            {
                faceEngine.unInit();
            }
        }
        Assert.isTrue(errorCode==ErrorInfo.MOK.getValue(),"人脸对比失败！");
        return faceSimilar.getScore()>=faceProperties.getScore();
    }

    public ImageInfo getImageInfo(File file) {
        ImageInfo imageInfo = getRGBData(file);
        return imageInfo;
    }
}
