package com.ycwl.basic.device.checker.impl;

import cn.hutool.core.date.DateUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.ListObjectsV2Request;
import com.aliyun.oss.model.ListObjectsV2Result;
import com.aliyun.oss.model.OSSObjectSummary;
import com.ycwl.basic.device.checker.IDeviceStatusChecker;
import com.ycwl.basic.device.checker.helper.CommonDeviceChecker;
import com.ycwl.basic.device.entity.alioss.DeviceAliOssConfig;
import com.ycwl.basic.device.entity.common.FileObject;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
public class AliOssDeviceChecker extends CommonDeviceChecker<DeviceAliOssConfig> implements IDeviceStatusChecker {
    public AliOssDeviceChecker(String configJson) {
        super(configJson);
    }

    private OSS getClient() {
        return new OSSClientBuilder().build(config.getEndpoint(), config.getAccessKeyId(), config.getAccessKeySecret());
    }

    private List<FileObject> getOssFileListByPrefix(String prefix) {
        OSS ossClient = getClient();
        ListObjectsV2Request listObjectsV2Request = new ListObjectsV2Request(config.getBucketName());
        listObjectsV2Request.setPrefix(config.getPrefix() + prefix);
        boolean isTruncated = true;
        String continuationToken = null;
        List<OSSObjectSummary> objectList = new ArrayList<>();
        try {
            while (isTruncated) {
                if (continuationToken != null) {
                    listObjectsV2Request.setContinuationToken(continuationToken);
                }

                // 列举文件。
                ListObjectsV2Result result = ossClient.listObjectsV2(listObjectsV2Request);

                objectList.addAll(result.getObjectSummaries());

                isTruncated = result.isTruncated();
                continuationToken = result.getNextContinuationToken();
            }
            return objectList.stream().filter(item -> item.getKey().endsWith(".ts")).map(item -> {
                FileObject object = new FileObject();
                object.setPath(item.getKey());
                object.setNeedDownload(true);
                String[] splitDir = item.getKey().split("/");
                String splitDate = splitDir[splitDir.length - 2];
                String splitName = splitDir[splitDir.length - 1];
                String[] splitExt = splitName.split("\\.", 2);
                String[] splitDt = splitExt[0].split("_", 2);
                String createTime = splitDt[0];
                String endTime = splitDt[1];
                object.setName(splitName);
                object.setEndTime(DateUtil.parse(splitDate+endTime, "yyyyMMddHHmmss"));
                object.setCreateTime(DateUtil.parse(splitDate+createTime, "yyyyMMddHHmmss"));
                return object;
            }).collect(Collectors.toList());
        } catch (OSSException e) {
            log.error("获取OSS文件列表失败", e);
        }
        return null;
    }
    @Override
    public boolean checkDeviceStatus() {
        Date now = new Date();
        if (deviceConfig.getOnlineMaxInterval() == null) {
            // 没有合适配置
            return true;
        }
        Date startTime = DateUtil.offsetMinute(now, -deviceConfig.getOnlineMaxInterval());
        List<FileObject> fileList = getOssFileListByPrefix(DateUtil.format(startTime, "yyyyMMdd/HHmm"));
        if (fileList != null) {
            return !fileList.isEmpty();
        } else {
            return false;
        }
    }
}
