package com.eitc.common.monitor;

import com.eitc.common.core.redis.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;

@Component
public class FileSizeMonitor {

    private final File file;
    private final Long totalBytes;

    @Autowired
    private RedisCache redisCache;


    public FileSizeMonitor() {
        this(null, null);
    }

    public FileSizeMonitor(File file, Long totalBytes) {
        this.file = file;
        this.totalBytes = totalBytes;
    }

    public void startMonitoring() {
       new Thread(() -> {
            try (FileInputStream fis = new FileInputStream(file);
                 FileChannel channel = fis.getChannel()) {
                while (true) {
                    long currentSize = channel.size();
                    long newSize = totalBytes - currentSize;
//                    lastSize.set(currentSize);
                    System.out.println("已下载：" + currentSize + "字节");
                    if (currentSize >= totalBytes) {
                        System.out.println("下载完成");
                        redisCache.setCacheObject("downloadStatus", "1");
                        break;
                    }
                    Thread.sleep(1000); // 每秒检查一次文件大小
                }
            } catch (IOException | InterruptedException e) {
                Thread.currentThread().interrupt();
                e.printStackTrace();
            }
        }).start();
    }

    public static void main(String[] args) {
        FileSizeMonitor monitor = new FileSizeMonitor(new File("F:\\Desktop\\fsdownload\\serverback.tar"),1l);
        monitor.startMonitoring();

    }
}
