package com.jpsoft.ehome.callback;

import com.sun.jna.Pointer;
import com.jpsoft.ehome.http.QueryStringDecoder;
import com.jpsoft.ehome.sdk.HCISUPCMS;
import com.jpsoft.ehome.sdk.HCISUPSS;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class LocalRWCallBack implements HCISUPSS.EHomeSSRWCallBack {
    private final int WRITE_ACTION = 0;
    private final int READ_ACTION = 1;
    private String picPath;

    public LocalRWCallBack(String picPath){
        this.picPath = picPath;
    }

    @Override
    public boolean invoke(int iHandle, byte byAct, Pointer pFileName, Pointer pFileBuf,
                          HCISUPSS.IntPointer dwFileLen, Pointer pRetUrl, Pointer pUser)
    {
        log.warn("cbEHomeSSRWCallBack, byAct："+ byAct);
        String strPath = this.picPath;
        String fileID = "";

        if(pRetUrl!=null) {
            byte[] byFileURL = new byte[256];
            System.arraycopy(pRetUrl.getByteArray(0, 256), 0, byFileURL, 0, 256);
            String fileUrl = new String(byFileURL).trim();

            QueryStringDecoder decoder = new QueryStringDecoder(fileUrl);

            Map<String, String> parameterMap = new HashMap<>();

            decoder.parameters().entrySet().forEach(entry -> {
                // entry.getValue()是一个List, 只取第一个元素
                parameterMap.put(entry.getKey(), entry.getValue().get(0));
            });

            fileID = parameterMap.get("id");
        }

        if(byAct == WRITE_ACTION) {
            byte[] byFileName = new byte[256];
            if (pFileName != null) {
                System.arraycopy(pFileName.getByteArray(0, 256), 0, byFileName, 0, 256);
            }

//          String strFilePath = strPath + "/" + new String(byFileName).trim();
            String newFileName = fileID + ".jpg";
            String strFilePath = strPath + "/" + newFileName;

            //若此目录不存在，则创建之
            File myPath = new File(strPath);

            if (!myPath.exists()) {
                myPath.mkdir();
                System.out.println("创建文件夹路径为：" + strPath);
            }

            log.warn("保存图片{},大小:{}", strFilePath, dwFileLen.dwData);

            if (dwFileLen.dwData > 0 && pFileBuf != null) {
                try {
                    FileOutputStream fout = new FileOutputStream(strFilePath);
                    //将字节写入文件
                    long offset = 0;
                    ByteBuffer buffers = pFileBuf.getByteBuffer(offset, dwFileLen.dwData);
                    byte[] bytes = new byte[dwFileLen.dwData];
                    buffers.rewind();
                    buffers.get(bytes);
                    fout.write(bytes);
                    fout.close();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }
        else if(byAct == READ_ACTION)
        {
            try {
                String strFilePath = strPath + "/" + fileID + ".jpg"; //根据上传保存的文件名下载

                File picFile = new File(strFilePath);

                if (picFile.exists()) {
                    FileInputStream picFileInput = new FileInputStream(picFile);

                    int picFileLen = picFileInput.available();

                    if (picFileLen < 0) {
                        System.out.println("input file dataSize < 0");
                        return false;
                    }

                    if (pFileBuf == null) //第一次回调
                    {
                        dwFileLen.dwData = picFileLen;  //测试文件大小
                        dwFileLen.write();
                    } else if (pFileBuf != null) {
                        HCISUPCMS.BYTE_ARRAY picByteArray = new HCISUPCMS.BYTE_ARRAY(picFileLen);
                        picFileInput.read(picByteArray.byValue);
                        picByteArray.write();

                        pFileBuf.write(0, picByteArray.byValue, 0, picByteArray.byValue.length);
                    }
                }
                else{
                    log.error("文件不存在!" + strFilePath);
                    return false;
                }
            } catch (IOException ex) {
                ex.fillInStackTrace();
            }
        }

        return true;
    }
}