package com.yutou.nas.utils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.yutou.nas.interfaces.DownloadInterface;
import com.yutou.nas.utils.StringUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class DepotManager {
    private DepotManager() {

    }

    public static void scan() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String str = HttpTools.get("http://tools.yutou233.cn/nas/depot/list.do?token=" + HttpTools.serverKey);
                if (!StringUtils.isEmpty(str)) {
                    JSONObject json = JSON.parseObject(str);
                    if (json.getInteger("code") == 1) {
                        JSONArray array = json.getJSONArray("data");
                        for (Object o : array) {
                            List<File> list = new ArrayList<>();
                            JSONObject item = JSON.parseObject(o.toString());
                            scanFile(new File(item.getString("path")), new DownloadInterface() {
                                @Override
                                public void onDownload(File file) {
                                    super.onDownload(file);
                                    list.add(file);
                                }
                            });
                            OSSManager.upload("oss-name-" + item.getString("type"), item.getString("path"), list.toArray(new File[0]));
                        }
                    }
                }
            }
        }).start();

    }

    private static void scanFile(File path, DownloadInterface interfaces) {
        if (!path.exists()) {
            interfaces.onError(new FileNotFoundException("没有该文件"));
            return;
        }
        for (File file : Objects.requireNonNull(path.listFiles())) {
            if (file.isDirectory()) {
                scanFile(file, interfaces);
            } else {
                interfaces.onDownload(file);
            }
        }
    }

    public static void main(String[] args) {
        List<File> list = new ArrayList<>();
        scanFile(new File("Z:\\相机"), new DownloadInterface() {
            @Override
            public void onDownload(File file) {
                super.onDownload(file);
                list.add(file);
            }
        });
        System.out.println("list = "+list.size());
    }
}
