package com.unibuy.smartdevice.worker;

import android.content.Context;
import androidx.annotation.NonNull;
import androidx.work.WorkManager;
import androidx.work.Worker;
import androidx.work.WorkerParameters;

import com.unibuy.smartdevice.MyApp;
import com.unibuy.smartdevice.exception.Logs;
import com.unibuy.smartdevice.external.HttpAPI;
import com.unibuy.smartdevice.external.StarCloudAPI;
import com.unibuy.smartdevice.tools.HttpConnect;
import com.unibuy.smartdevice.tools.Tools;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class UploadLogPeriodicWorker extends Worker {
    private Logs logs;
    private static int timeinByMinute;

    static {
        timeinByMinute = 10;
    }

    public static int getTimeinByMinute() {
        return timeinByMinute;
    }

    public UploadLogPeriodicWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
        super(context, workerParams);
        logs = new Logs(getClass());
    }

    @NonNull
    @Override
    public Result doWork() {
        logs.debug("進入背景工作:"+getClass().getSimpleName()+" "+getId());

        if (MyApp.getInstance().isMachineBusy()) {
            logs.debug("系統使用中，延後處理備份事項");

            return Result.retry();
        }

        if (MyApp.getInstance().getMachine().getMachineID().isEmpty()) {
            logs.debug("背景工作執行失敗:沒有機器序號，使用暫時序號 00000000");
            StarCloudAPI.updateOnDomainNameByNewHost = StarCloudAPI.domainNameByNewHost + "api/machine/00000000/log/update";
        } else {
            StarCloudAPI.updateOnDomainNameByNewHost = StarCloudAPI.domainNameByNewHost + "api/machine/" + MyApp.getInstance().getMachine().getMachineID() + "/log/update";
        }

        logs.debug("url:" + StarCloudAPI.updateOnDomainNameByNewHost);

        File txtDebug = new File(Tools.getExternalFilesDir(), "debug.txt");

        // 1. 旋轉目前的 debug.txt
        if (txtDebug.exists() && txtDebug.length() > 0) {
            String yyyyMMddHHmmByNow = Tools.getStringByNow("yyyyMMddHHmm");
            if (yyyyMMddHHmmByNow.length() == 12) {
                yyyyMMddHHmmByNow = yyyyMMddHHmmByNow.substring(0, 11) + "0";
            }
            // 加上毫秒時間戳記，確保檔名在任何情況下都唯一，防止 renameTo 失敗
            String uniqueFileName = yyyyMMddHHmmByNow + "_" + System.currentTimeMillis() + ".txt";
            File newFile = new File(Tools.getExternalFilesDir(), uniqueFileName);

            boolean renamed = txtDebug.renameTo(newFile);
            logs.debug("newFile:" + newFile.getAbsolutePath() + " renamed:" + renamed);

            if (!renamed) {
                logs.debug("重新命名日誌檔失敗，將重試。");
                return Result.retry();
            }
        }

        // 2. 掃描 ExternalFilesDir 批次補上傳非 active 的所有 txt 日誌檔
        File dir = Tools.getExternalFilesDir();
        boolean anyUploadFailed = false;
        if (dir != null && dir.exists()) {
            File[] files = dir.listFiles((d, name) -> name.endsWith(".txt")
                    && !name.equals("debug.txt")
                    && !name.equals("crash_pending.txt"));

            if (files != null && files.length > 0) {
                logs.debug("發現待上傳歷史日誌共 " + files.length + " 個，開始批次上傳。");
                HttpConnect httpConnect = new HttpConnect();
                for (File file : files) {
                    boolean success = httpConnect.uploadFile(StarCloudAPI.updateOnDomainNameByNewHost, file);
                    if (!success) {
                        logs.debug("檔案上傳失敗，保留至下次重試：" + file.getName());
                        anyUploadFailed = true;
                    }
                }
            }
        }

        if (anyUploadFailed) {
            logs.debug("部分歷史日誌上傳失敗，排程重試中。");
            return Result.retry();
        }

        return Result.success();
    }
}