package com.afanticar.aliyun.fc;

import cn.hutool.http.HttpUtil;
import com.afanticar.aliyun.fc.dto.request.SimpleRequest;
import com.afanticar.aliyun.fc.dto.response.SimpleResponse;
import com.afanticar.aliyun.fc.util.FFmpegUtil;
import com.aliyun.fc.runtime.Context;
import com.aliyun.fc.runtime.Credentials;
import com.aliyun.fc.runtime.PojoRequestHandler;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.Date;
import java.util.UUID;

/**
 * @Author: wuzhancai
 * @Desc: hello
 * @Date: 2023/6/2 13:55
 */
public class HelloFC implements PojoRequestHandler<SimpleRequest, SimpleResponse> {

    private static final Logger log = LoggerFactory.getLogger(HelloFC.class);

    private static String ffmpegPath="/code/ffmpeg";

    static {
        try{
            String result = FFmpegUtil.assignmentFfmpegAuthority(ffmpegPath);
            log.info("result {}",result);
        }catch (Exception e){
            log.error("ffmpeg init fail {}",e);
        }
    }

    @Override
    public SimpleResponse handleRequest(SimpleRequest request, Context context) {
        String message = getAudio(request,context);
        return new SimpleResponse(message);
    }

    public static void main(String[] args) {
        SimpleRequest request = new SimpleRequest();
        Date beginDate = new Date();
        log.info("begin time {}",beginDate);
        log.warn("dfdfdf");
        String audio = getAudio(request,null);
        Date endDate = new Date();
        log.info("end time {} user {} ",endDate,(endDate.getTime()-beginDate.getTime()));
        System.out.println(audio);
    }

    private static String getAudio(SimpleRequest request,Context context) {
        String message = "Hello, " + request.getFirstName() + " " + request.getLastName();
        log.info("helloo execute 111");

        String url = "https://api.amemv.com/aweme/v1/play/?video_id=v0200fg10000cgbkfqjc77u3udkfff30&line=1&file_id=db82e40c28ad49fb860a247ace95f8b8&sign=44b50f681b684101c3f33ce7c25ffd02&is_play_url=1&source=PackSourceEnum_PUBLISH";
        String folderPath = "/usr/aweme";
        File file = new File(folderPath);
        if(!file.exists()){
            file.mkdirs();
        }
        String outputFilePath = folderPath+"/aa.wav";


//        if(context != null){
            // Bucket名称, 需要预先创建。
            String bucketName = "cont-aweme-dev";
            // Endpoint必须填写Bucket所在地域对应的Endpoint，推荐使用内网访问地址。以华东1（杭州）为例，内网访问Endpoint为https://oss-cn-hangzhou-internal.aliyuncs.com。
            String endpoint = "https://oss-cn-hangzhou-internal.aliyuncs.com";
//            String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";

            // 获取密钥信息，执行前，确保函数所在的服务配置了角色信息，并且角色需要拥有AliyunOSSFullAccess权限。
            // 建议直接使用AliyunFCDefaultRole角色。
        String os = System.getProperty("os.name");
        if(os.toLowerCase().indexOf("win")!=-1){
            ffmpegPath = null;
            endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        }
        FFmpegUtil.live2Audio(ffmpegPath,url,"/code/temp/aa.wav",null,null);
        log.info("context {}", context);
        Credentials creds = null;
        if(context != null){
            creds = context.getExecutionCredentials();
            log.info("creds.getAccessKeyId{},creds.getAccessKeySecret{},creds.getSecurityToken{}",creds.getAccessKeyId(),creds.getAccessKeySecret(),creds.getSecurityToken());
        }

        OSS ossClient =null;
        if(context != null){
            ossClient = new OSSClientBuilder().build(endpoint, creds.getAccessKeyId(), creds.getAccessKeySecret(),creds.getSecurityToken());
        }else{
            ossClient = new OSSClientBuilder().build(endpoint, "LTAI5tLJxsRWWNkT3tvCD4fS", "0VETCYESe4J11ejEovggjnc5prrHq8");
        }

            // 填写Byte数组。
            byte[] content = "Hello FC".getBytes();
            // 依次填写Bucket名称（例如examplebucket）和Object完整路径（例如exampledir/exampleobject.txt）。Object完整路径中不能包含Bucket名称。
//            ossClient.putObject(bucketName, "exampledir/"+UUID.randomUUID().toString()+".txt", new ByteArrayInputStream(content));
            ossClient.putObject(bucketName, "exampledir/"+ UUID.randomUUID().toString() +".wav",new File("/code/temp/aa.wav"));


            // 关闭OSSClient。
            ossClient.shutdown();

//            outputStream.write(new String("done").getBytes());
        String body = "{\"ctime\":\"\",\"env\":\"\",\"equipmentId\":\"\",\"eventResult\":\"\",\"eventStep\":\"\",\"frameId\":\"\",\"platform\":\"\",\"roomId\":\"ff\",\"taskId\":\"aliyunfcc\",\"taskName\":\"\",\"time\":0}";
        String post = HttpUtil.post("https://api-dev.afanticar.com/content-center/v1/kaize/publish/task", body);
        log.info("post {}",post);

        //获取当前堆的大小 byte 单位
        long heapSize = Runtime.getRuntime().totalMemory();
        log.info("Current heap size{}m",heapSize/1024/1024);

        //获取堆的最大大小byte单位
        //超过将抛出 OutOfMemoryException
        long heapMaxSize = Runtime.getRuntime().maxMemory();
        log.info("Gets the maximum heap size{}m",heapMaxSize/1024/1024);

        //获取当前空闲的内存容量byte单位
        long heapFreeSize = Runtime.getRuntime().freeMemory();
        log.info("Gets the current free memory capacity{}m",heapFreeSize/1024/1024);

        System.gc();

        log.info("gc-after");

        heapSize = Runtime.getRuntime().totalMemory();
        log.info("Current heap size{}m",heapSize/1024/1024);

        //获取堆的最大大小byte单位
        //超过将抛出 OutOfMemoryException
        heapMaxSize = Runtime.getRuntime().maxMemory();
        log.info("Gets the maximum heap size{}m",heapMaxSize/1024/1024);

        //获取当前空闲的内存容量byte单位
        heapFreeSize = Runtime.getRuntime().freeMemory();
        log.info("Gets the current free memory capacity{}m",heapFreeSize/1024/1024);

        System.gc();

        return message;
    }


}
