package com.unibuy.smartdevice.worker;

import android.app.Application;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;

import androidx.work.BackoffPolicy;
import androidx.work.ExistingWorkPolicy;
import androidx.work.OneTimeWorkRequest;
import androidx.work.WorkManager;

import com.unibuy.smartdevice.exception.Logs;
import com.unibuy.smartdevice.ui.FontendActivity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

public class AppCrashHandler implements Thread.UncaughtExceptionHandler {
    private final Application application;
    private Logs logs;

    private Thread.UncaughtExceptionHandler mDefaultHandler;

    public AppCrashHandler(Application application) {
        this.application = application;
        logs = new Logs(getClass());
        this.mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
    }

    @Override
    public void uncaughtException(Thread thread, Throwable throwable) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        throwable.printStackTrace(pw);
        String crashInfo = sw.toString();

        logs.info("============================ crash ============================");
        logs.update("crashInfo", crashInfo);

        try {
            File crashLogFile = new File(application.getExternalFilesDir(null), "crash_pending.txt");
            FileOutputStream fos = new FileOutputStream(crashLogFile);
            fos.write(crashInfo.getBytes(StandardCharsets.UTF_8));
            fos.close();
        } catch (IOException e) {
            logs.warning(e);
        }

        Intent intent = new Intent(application, FontendActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        application.startActivity(intent);

        new Handler(Looper.getMainLooper()).postDelayed(() -> {
            android.os.Process.killProcess(android.os.Process.myPid());
            System.exit(1);
        }, 2000);

        OneTimeWorkRequest oneTimeWorkRequest = new OneTimeWorkRequest.Builder(UploadLogOneTimeWorker.class).build();
        WorkManager.getInstance(application).enqueueUniqueWork(
                "oneTimeWorkRequest",  // 設定唯一名稱，避免重複
                ExistingWorkPolicy.REPLACE,
                oneTimeWorkRequest
        );
    }
}
