package com.jpsoft.ehome.callback;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.sun.jna.Pointer;
import com.jpsoft.ehome.http.QueryStringDecoder;
import com.jpsoft.ehome.sdk.HCISUPSS;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Map;

/**
 * 该方案只节省了磁盘存储空间，没有节省流量
 */
@Slf4j
public class OSSRWCallBack implements HCISUPSS.EHomeSSRWCallBack {
    private final int WRITE_ACTION = 0;
    private final int READ_ACTION = 1;

    private String accessKeyId = "LTAIXIyrXmjgOXQa";
    private String accessKeySecret = "B0RS3zHLct8OKKIDu2HREaVx6RXgWL";
    private String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
    private String bucketName = "rccs";
    private String objectPre = "ess";
    private String urlPrefix = "http://oss.xiaoxinda.com";

    @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 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();

            log.warn("pRetUrl=" +  fileUrl);

            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 (StringUtils.isEmpty(fileID)){
            return false;
        }

        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";

            if (dwFileLen.dwData > 0 && pFileBuf != null) {
                try {
                    OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

                    long offset = 0;
                    ByteBuffer buffers = pFileBuf.getByteBuffer(offset, dwFileLen.dwData);
                    byte[] bytes = new byte[dwFileLen.dwData];
                    buffers.rewind();
                    buffers.get(bytes);

                    ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);

                    // 上传文件流
                    ossClient.putObject(bucketName, objectPre + "/" + newFileName, inputStream);

                    // 关闭OSSClient
                    ossClient.shutdown();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }
        else if(byAct == READ_ACTION)
        {
            try {
                String filePath = objectPre + "/" + fileID + ".jpg"; //根据上传保存的文件名下载

                OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

                boolean exist = false;

                try {
                    exist = ossClient.doesObjectExist(bucketName, filePath);
                }
                catch (Exception innerEx){
                    log.error(innerEx.getMessage());
                }

                if (exist) {
                    int picFileLen = (int)ossClient.getObjectMetadata(bucketName,filePath).getContentLength();

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

                    if (pFileBuf == null) //第一次回调
                    {
                        dwFileLen.dwData = picFileLen;  //测试文件大小
                        dwFileLen.write();
                    } else if (pFileBuf != null) {
                        //采用CDN地址下载
                        String fileUrl = urlPrefix + "/" + filePath;
                        URL url = new URL(fileUrl);

                        ByteArrayOutputStream data = new ByteArrayOutputStream();
                        byte[] buffs = new byte[1024 * 10];

                        //创建连接
                        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                        conn.setRequestMethod("GET");
                        conn.setConnectTimeout(5000);

                        InputStream input = conn.getInputStream();

                        //将内容读到内存中
                        int len = -1;

                        while ((len =input.read(buffs))!=-1){
                            data.write(buffs,0,len);
                        }

                        input.close();

                        byte[] buffer = data.toByteArray();

                        pFileBuf.write(0, buffer, 0, buffer.length);
                    }
                }
                else{
                    log.error("文件不存在!" + filePath);
                    return false;
                }
            } catch (IOException ex) {
                log.error(ex.getMessage(),ex);
            }
        }

        return true;
    }
}