package com.jpsoft.ehome.callback;

import com.sun.jna.Pointer;
import com.sun.jna.ptr.IntByReference;
import com.jpsoft.ehome.sdk.HCISUPSS;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;

/**
 * 采用该接口需要将链接库切换成修改url的版本
 */
public class CustomWCallBack implements HCISUPSS.UrlRWCallBackEx {
    @Override
    public boolean invoke(int iHandle, byte byAct, Pointer pFileName, Pointer pFileBuf, IntByReference dwFileLen, Pointer pFileUrl, Pointer pRetUrl, Pointer pUser)
    {
        String strPath = "C://EhomePicServer/";

        byte[] byFileName = new byte[256];
        System.arraycopy(pFileName.getByteArray(0, 256), 0, byFileName, 0, 256);
        String strFilePath = strPath + new String(byFileName).trim();

        //若此目录不存在，则创建之
        File myPath = new File(strPath);
        if ( !myPath.exists()){
            myPath.mkdir();
            System.out.println("创建文件夹路径为："+ strPath);
        }

        if (dwFileLen.getValue() > 0 && pFileBuf != null)
        {
            FileOutputStream fout;
            try {
                fout = new FileOutputStream(strFilePath);
                //将字节写入文件
                long offset = 0;
                ByteBuffer buffers = pFileBuf.getByteBuffer(offset, dwFileLen.getValue());
                byte [] bytes = new byte[dwFileLen.getValue()];
                buffers.rewind();
                buffers.get(bytes);
                fout.write(bytes);
                fout.close();
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        //URL由平台自行生成
        String strRetPath = "/attphoto/2020-04-26/c2604913-2ef9-4c0a-8cc1-2ad9e44b3e4d.jpg";
        int iLenURL = strRetPath.getBytes().length;
        pRetUrl.write(0, strRetPath.getBytes(), 0, iLenURL);

        return true;
    }
}
