package com.fs.course.service.impl;


import com.volcengine.helper.VodUploadProgressEvent;
import com.volcengine.helper.VodUploadProgressListener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.concurrent.TimeUnit;

@Slf4j
public class VodUploadMediaProcessListener implements VodUploadProgressListener {

    private long bytesUploaded = 0;
    private long fileSize = -1;

    private final String uploadId;
    private final RedisTemplate<String, Object> redisTemplate;

    public VodUploadMediaProcessListener(String uploadId,
                                         RedisTemplate redisTemplate) {
        this.uploadId = uploadId;
        this.redisTemplate = redisTemplate;
    }

    @Override
    public void progressChanged(VodUploadProgressEvent event) {
        switch (event.getEventType()) {
            case FILE_SIZE_EVENT:
                fileSize = event.getByteSize();
                break;

            case UPLOAD_BYTES_EVENT:
                bytesUploaded += event.getByteSize();
                if (fileSize > 0) {
                    int percent = Math.min(
                            (int) (bytesUploaded * 100.0 / fileSize),
                            100
                    );
                    redisTemplate.opsForValue()
                            .set("vod:upload:" + uploadId, percent, 10, TimeUnit.MINUTES);
                    log.info("uploadId={} progress={}%", uploadId, percent);
                }
                break;
        }
    }
}
