package com.izouma.awesomeadmin.vuforia;

import com.google.gson.Gson;
import com.izouma.awesomeadmin.dto.wx.TemplateMessage;
import com.izouma.awesomeadmin.model.VuforiaTarget;
import com.izouma.awesomeadmin.util.MbappUtil;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.*;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.cookie.DateUtils;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.apache.xmlbeans.impl.xb.xsdschema.Public;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 * Vuforia工具类
 *
 * @author
 */
@Service
public class VuforiaUtil {

    private final static String VUFORIA_URL = "https://vws.vuforia.com";

    private static Logger logger = Logger.getLogger(VuforiaUtil.class);


    /**
     * 新增识别图
     *
     * @param imageUrl   图片地址
     * @param targetName 识别图名称
     * @param width      宽度
     * @param accessKey  key
     * @param secretKey  密钥
     * @return
     */
    public static String PostNewTarget(String imageUrl, String targetName, double width, String accessKey, String secretKey) {

        try {
            HttpPost postRequest = new HttpPost();
            HttpClient client = new DefaultHttpClient();
            postRequest.setURI(new URI(VUFORIA_URL + "/targets"));
            JSONObject requestBody = new JSONObject();

            byte[] image = readImg(imageUrl);
            requestBody.put("name", targetName); // Mandatory
            requestBody.put("width", width); // Mandatory
            requestBody.put("image", Base64.encodeBase64String(image)); // Mandatory
            requestBody.put("active_flag", 1); // Optional
            requestBody.put("application_metadata", Base64.encodeBase64String("Vuforia test metadata".getBytes())); // Optional

            postRequest.setEntity(new StringEntity(requestBody.toString()));
            //setHeaders(postRequest); // Must be done after setting the body
            SignatureBuilder sb = new SignatureBuilder();
            postRequest.setHeader(new BasicHeader("Date", DateUtils.formatDate(new Date()).replaceFirst("[+]00:00$", "")));
            postRequest.setHeader(new BasicHeader("Content-Type", "application/json"));
            postRequest.setHeader("Authorization", "VWS " + accessKey + ":" + sb.tmsSignature(postRequest, secretKey));

            HttpResponse response = client.execute(postRequest);
            String responseBody = EntityUtils.toString(response.getEntity());
            System.out.println(responseBody);

            JSONObject jobj = new JSONObject(responseBody);

            String uniqueTargetId = jobj.has("target_id") ? jobj.getString("target_id") : "";
            System.out.println("\nCreated target with id: " + uniqueTargetId);

            return uniqueTargetId;
        } catch (Exception e) {
            logger.error("PostNewTarget 新增识别图 异常", e);

        }
        return null;
    }


    public static String updateTarget(String targetId, String targetName, double width, String imageUrl, String accessKey, String secretKey, Boolean b) {

        try {
            HttpPut putRequest = new HttpPut();
            HttpClient client = new DefaultHttpClient();
            putRequest.setURI(new URI(VUFORIA_URL + "/targets/" + targetId));
            JSONObject requestBody = new JSONObject();

            if (StringUtils.isNotEmpty(targetName)) {

                requestBody.put("name", targetName); // Mandatory
            }

            if (width > 0) {
                requestBody.put("width", width); // Mandatory
            }

            if (StringUtils.isNotEmpty(imageUrl)) {

                byte[] image = readImg(imageUrl);
                requestBody.put("image", Base64.encodeBase64String(image)); // Mandatory
            }

            if (b != null) {
                requestBody.put("active_flag", b);// add a JSON field for the active_flag
            }


            putRequest.setEntity(new StringEntity(requestBody.toString()));
            //setHeaders(putRequest); // Must be done after setting the body

            SignatureBuilder sb = new SignatureBuilder();
            putRequest.setHeader(new BasicHeader("Date", DateUtils.formatDate(new Date()).replaceFirst("[+]00:00$", "")));
            putRequest.setHeader(new BasicHeader("Content-Type", "application/json"));
            putRequest.setHeader("Authorization", "VWS " + accessKey + ":" + sb.tmsSignature(putRequest, secretKey));


            HttpResponse response = client.execute(putRequest);
            String resultStr = EntityUtils.toString(response.getEntity());
            System.out.println(resultStr);

            JSONObject jobj = new JSONObject(resultStr);

            String result_code = jobj.has("result_code") ? jobj.getString("result_code") : "";

            return result_code;
        } catch (Exception e) {
            logger.error("updateTarget 更新识别图异常", e);
        }
        return null;
    }

    /**
     * 删除
     *
     * @param targetId
     * @param accessKey
     * @param secretKey
     */
    public static String deleteTarget(String targetId, String accessKey, String secretKey) {

        try {


            HttpDelete deleteRequest = new HttpDelete();
            HttpClient client = new DefaultHttpClient();
            deleteRequest.setURI(new URI(VUFORIA_URL + "/targets/" + targetId));

            SignatureBuilder sb = new SignatureBuilder();
            deleteRequest.setHeader(new BasicHeader("Date", DateUtils.formatDate(new Date()).replaceFirst("[+]00:00$", "")));
            deleteRequest.setHeader("Authorization", "VWS " + accessKey + ":" + sb.tmsSignature(deleteRequest, secretKey));

            HttpResponse response = client.execute(deleteRequest);
            String resultStr = EntityUtils.toString(response.getEntity());
            System.out.println(resultStr);

            JSONObject jobj = new JSONObject(resultStr);

            String result_code = jobj.has("result_code") ? jobj.getString("result_code") : "";

            return result_code;

        } catch (Exception e) {
            logger.error("deleteTarget 删除识别图异常", e);
        }
        return null;
    }

    /**
     * 获取基本信息
     *
     * @param targetId
     * @param accessKey
     * @param secretKey
     * @return
     */
    public static VuforiaTarget getTarget(String targetId, String accessKey, String secretKey) {

        try {


            HttpGet getRequest = new HttpGet();
            HttpClient client = new DefaultHttpClient();
            getRequest.setURI(new URI(VUFORIA_URL + "/targets/" + targetId));

            SignatureBuilder sb = new SignatureBuilder();
            getRequest.setHeader(new BasicHeader("Date", DateUtils.formatDate(new Date()).replaceFirst("[+]00:00$", "")));
            getRequest.setHeader("Authorization", "VWS " + accessKey + ":" + sb.tmsSignature(getRequest, secretKey));

            HttpResponse response = client.execute(getRequest);
            String resultStr = EntityUtils.toString(response.getEntity());
            System.out.println(resultStr);

            JSONObject jobj = new JSONObject(resultStr);

            String result_code = jobj.has("result_code") ? jobj.getString("result_code") : "";

            if (StringUtils.isNotEmpty(result_code)) {
                if ("Success".equals(result_code)) {
                    JSONObject job = jobj.getJSONObject("target_record");

                    VuforiaTarget vuforiaTarget = new VuforiaTarget();

                    vuforiaTarget.setTargetId(job.getString("target_id"));
                    vuforiaTarget.setActiveFlag(job.getBoolean("active_flag"));
                    vuforiaTarget.setName(job.getString("name"));
                    vuforiaTarget.setWidth(job.getDouble("width"));
                    vuforiaTarget.setTrackingRating(job.getInt("tracking_rating"));
                    vuforiaTarget.setRecoRating(job.getString("reco_rating"));

                    return vuforiaTarget;

                }
            }

        } catch (Exception e) {
            logger.error("getTarget 获取识别图异常", e);
        }
        return null;
    }


    public static byte[] readImg(String urlOrPath) {

        Logger logger = Logger.getLogger(FileUtils.class);
        byte[] imgBytes = new byte[1024 * 1024];

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        BufferedInputStream reader = null;
        InputStream in = null;
        URLConnection conn = null;
        File temFile = null;

        try {
            if (!urlOrPath.startsWith("http:")) {
                File imgFile = new File(urlOrPath);
                if (!imgFile.isFile() || !imgFile.exists() || !imgFile.canRead()) {
                    logger.info("图片不存在或不可读");
                    return new byte[0];
                }
                in = new FileInputStream(imgFile);
            } else {
                URL imgUrl = new URL(urlOrPath);
                conn = imgUrl.openConnection();
                temFile = new File(new Date().getTime() + MbappUtil.create_nonce_str() + ".jpg");
                FileOutputStream tem = new FileOutputStream(temFile);
                BufferedImage image = ImageIO.read(conn.getInputStream());
                ImageIO.write(image, "jpg", tem);
                in = new FileInputStream(temFile);
            }
            reader = new BufferedInputStream(in);
            byte[] buffer = new byte[1024];
            while (reader.read(buffer) != -1) {
                out.write(buffer);
            }
            imgBytes = out.toByteArray();

        } catch (Exception e) {
            logger.error("读取图片发生异常", e);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            try {
                out.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            if (temFile != null) {
                temFile.delete();
            }
        }
        return imgBytes;
    }


}
