package com.fdkanfang.common.util;

import com.fdkanfang.common.constant.ConstantCmd;
import com.fdkanfang.common.constant.ConstantFileName;
import com.fdkanfang.common.constant.ConstantFilePath;
import com.fdkanfang.common.proto.Common;
import com.fdkanfang.common.proto.BigSceneProto.binary_mesh;
import com.fdkanfang.common.proto.Visionmodeldata;
import com.fdkanfang.common.proto.format.JsonFormat;
import com.google.protobuf.TextFormat;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;

import java.io.*;

/**
 * Created by Owen on 2019/12/17 0017 11:40
 */
@Log4j2
public class CreateObjUtil {


    /**
     * 调用算法 xx.sh 脚本
     * @param command
     */
    public static void callshell(String command){
        try {
            Process process = Runtime.getRuntime().exec(command);
            StreamGobbler errorGobbler = new StreamGobbler(process.getErrorStream(), "ERROR");
            errorGobbler.start();
            StreamGobbler outGobbler = new StreamGobbler(process.getInputStream(), "STDOUT");
            outGobbler.start();
            process.waitFor();
        } catch (Exception e) {
            log.error("执行垂直校验算法脚本出现错误:{}" , e);
            e.printStackTrace();
        }
    }


    public static void convertTxtToDam(String srcpath,String despath)throws Exception
    {
        try
        {
            binary_mesh.Builder builder= binary_mesh.newBuilder();
            InputStream inputStream = new FileInputStream(srcpath);
            InputStreamReader reader = new InputStreamReader(inputStream, "ASCII");
            TextFormat.merge(reader, builder);
            byte[] buf= builder.build().toByteArray();


            //把序列化后的数据写入本地磁盘
            ByteArrayInputStream stream = new ByteArrayInputStream(buf);
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(despath));//设置输出路径
            BufferedInputStream bis = new BufferedInputStream(stream);
            int b = -1;
            while ((b = bis.read()) != -1) {
                bos.write(b);
            }
            bis.close();
            bos.close();
        }
        catch(Exception e)
        {
            StringWriter trace=new StringWriter();
            e.printStackTrace(new PrintWriter(trace));
            log.error(trace.toString());
        }
    }


    public static void convertDamToLzma(String folderName)throws Exception {
        log.info("folderName: {}", folderName);
        try {
            String command = "lzma "+ folderName + ConstantFileName.modelUUID+"_50k.dam";
            log.info("开始转换lzma ：{}", command );
            callshell(command);
            log.info("转换lzma完毕");
        }
        catch(Exception e)
        {
            StringWriter trace=new StringWriter();
            e.printStackTrace(new PrintWriter(trace));
            log.error(trace.toString());
        }

    }


    public static void convertTxtToVisionmodeldata(String srcpath,String despath)throws Exception
    {
        try
        {
            Visionmodeldata.NavigationInfo.Builder builder = Visionmodeldata.NavigationInfo.newBuilder();
            String jsonFormat = readTxtFileToJson(srcpath);
            JsonFormat.merge(jsonFormat, builder);
            byte[] buf= builder.build().toByteArray();

            //把序列化后的数据写入本地磁盘
            ByteArrayInputStream stream = new ByteArrayInputStream(buf);
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(despath));//设置输出路径
            BufferedInputStream bis = new BufferedInputStream(stream);
            int b = -1;
            while ((b = bis.read()) != -1) {
                bos.write(b);
            }
            bis.close();
            bos.close();
        }
        catch(Exception e)
        {
            StringWriter trace=new StringWriter();
            e.printStackTrace(new PrintWriter(trace));
            log.error(trace.toString());
        }
    }

    public static String readTxtFileToJson(String filePath){
        try {
            String encoding="UTF-8";
            File file=new File(filePath);
            if(file.isFile() && file.exists()){
                InputStreamReader read = new InputStreamReader(
                        new FileInputStream(file),encoding);
                BufferedReader bufferedReader = new BufferedReader(read);
                String lineTxt = null;
                String result="";
                while((lineTxt = bufferedReader.readLine()) != null){
                    result+=lineTxt;
                    //log.info(lineTxt);
                }
                read.close();
                return result;
            }else{
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    //开始建模
    public static void build3dModel(String folderName,String isModel) throws Exception{
        log.info("开始建模");
        String command = ConstantCmd.BUILD_MODEL_COMMAND+folderName;
        // cmd: bash /home/ubuntu/bin/Launcher.sh /data/kanfang/10002/pano
        log.info("cmd: {}",command);
        callshell(command);
        log.info("计算完毕：" + command);
    }

    public static void convertTxtToVisionmodeldataCommon(String srcpath,String despath)throws Exception
    {
        try
        {
            Common.NavigationInfo.Builder builder = Common.NavigationInfo.newBuilder();
            String jsonFormat = readTxtFileToJson(srcpath);
            log.warn("jsonFormat: {}", jsonFormat);

            // 临时处理，等算法处理好这个问题，可以删除此方法
//            jsonFormat = deviceJson(jsonFormat);

            JsonFormat.merge(jsonFormat, builder);
            byte[] buf= builder.build().toByteArray();

            //把序列化后的数据写入本地磁盘
            ByteArrayInputStream stream = new ByteArrayInputStream(buf);
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(despath));//设置输出路径
            BufferedInputStream bis = new BufferedInputStream(stream);
            int b = -1;
            while ((b = bis.read()) != -1) {
                bos.write(b);
            }
            bis.close();
            bos.close();
        }
        catch(Exception e)
        {
            StringWriter trace=new StringWriter();
            e.printStackTrace(new PrintWriter(trace));
            log.error(trace.toString());
        }
    }


    private static String deviceJson(String str) {
        String rep = "\"device\":vision_\\d,";
        if (str.contains("\"device\":vision")) {
            log.warn("device 临时特殊处理一下");
            str = StringUtils.replaceAll(str, rep, "");
        }
        log.info("update json: {}", str);
        return str;
    }

    public static void main(String[] args) {
//        String str = "{\n" +
//                "\"sweepLocations\":[\n" +
//                "\t{\"id\":0,\"uuid\":\"20190902113922_pano\",\"pose\":{\"rotation\":{\"x\":0.0084254265774,\"y\":-0.0049948093426,\"z\":0.7472423668825,\"w\":-0.6644794272229},\"translation\":{\"x\":2.788870573044,\"y\":-0.1210948259866,\"z\":-0.2305315136909}},\"puck\":{\"x\":2.788870573044,\"y\":-0.1210948259866,\"z\":-1.830531513691},\"group\":1,\"subgroup\":1,\"device\":vision_0,\"subdevice\":0,\"visibles\":[],\"visibles2\":[0],\"visibles3\":[]}\n" +
//                ",\t{\"id\":1,\"uuid\":\"20190902114058_pano\",\"pose\":{\"rotation\":{\"x\":-0.0046730438002,\"y\":-0.0126436814496,\"z\":0.6898098282658,\"w\":0.7238651123026},\"translation\":{\"x\":-3.211129426956,\"y\":-0.0866986662149,\"z\":-0.2468997687101}},\"puck\":{\"x\":-3.211129426956,\"y\":-0.0866986662149,\"z\":-1.84689976871},\"group\":2,\"subgroup\":1,\"device\":vision_1,\"subdevice\":0,\"visibles\":[],\"visibles2\":[1],\"visibles3\":[0]}\n" +
//                "]\n" +
//                "}\n";
//
//        deviceJson(str);

        // param1：输入文件， param2：输出文件；
        String path = "C:\\Users\\Administrator\\Desktop\\test\\d_Klqyie3sQ\\pano\\extras\\";
        try {
            convertTxtToVisionmodeldata(path+"vision.txt", path+"vision.modeldata");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }





}
