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.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");
            HttpAPI.updateOnDomainNameByNewHost = HttpAPI.domainNameByNewHost + "api/machine/00000000/log/update";
        } else {
            HttpAPI.updateOnDomainNameByNewHost = HttpAPI.domainNameByNewHost + "api/machine/" + MyApp.getInstance().getMachine().getMachineID() + "/log/update";
        }

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

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

        String yyyyMMddHHmmByNow = Tools.getStringByNow("yyyyMMddHHmm");
        if (yyyyMMddHHmmByNow.length() == 12) {
            yyyyMMddHHmmByNow = yyyyMMddHHmmByNow.substring(0, 11) + "0";
        }
        File newFile = new File(Tools.getExternalFilesDir(), yyyyMMddHHmmByNow + ".txt");

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

            if (renamed) {
                HttpConnect httpConnect = new HttpConnect();
                httpConnect.uploadFile(HttpAPI.updateOnDomainNameByNewHost, newFile);
            } else {
                return Result.retry();
            }
        }

        return Result.success();
    }
}