package com.unibuy.smartdevice.ui;

import android.content.Context;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.work.BackoffPolicy;
import androidx.work.ExistingWorkPolicy;
import androidx.work.OneTimeWorkRequest;
import androidx.work.WorkManager;

import com.unibuy.smartdevice.AppCompatActivityAbstract;
import com.unibuy.smartdevice.MyApp;
import com.unibuy.smartdevice.databinding.ActivityDebugBinding;
import com.unibuy.smartdevice.tools.HandlerMain;
import com.unibuy.smartdevice.tools.ToastHandlerMain;
import com.unibuy.smartdevice.tools.Tools;
import com.unibuy.smartdevice.ui.recycler.RecyclerDebugAdpter;
import com.unibuy.smartdevice.worker.UploadLogOneTimeWorker;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Deque;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class DebugActivity extends AppCompatActivityAbstract {
    private ActivityDebugBinding binding;
    private List<String> statusList = new ArrayList<>();
    private RecyclerDebugAdpter recyclerDebugAdpter;
    private static final int BATCH_SIZE = 50; // 每次讀取的行數
    private Deque<String> buffer = new ArrayDeque<>(); // 讀取緩存
    private boolean isLoading = false; // 是否正在加載
    private boolean isEndOfFile = false; // 是否到達文件底部
    private Thread loadingThread; // 當前加載的線程

    @Override
    protected Context setCtx() {
        return this;
    }

    @Override
    protected Class<?> setCls() {
        return getClass();
    }

    @Override
    protected HandlerMain setHandlerMain() {
        return new ToastHandlerMain(getCtx(), getLogs());
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityDebugBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        recyclerDebugAdpter = new RecyclerDebugAdpter(statusList);
        binding.recyclerDebugList.setAdapter(recyclerDebugAdpter);
        binding.recyclerDebugList.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));

        // 監聽 RecyclerView 滑動事件
        binding.recyclerDebugList.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                if (layoutManager != null) {
                    int totalItemCount = layoutManager.getItemCount();
                    int lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition();

                    // 當滑動到列表底部 5 行內時，自動加載更多日誌
                    if (lastVisibleItemPosition >= totalItemCount - 5 && !isLoading) {
                        loadMoreLines();
                    }
                }
            }
        });

        binding.buttonBack.setOnClickListener(v -> {
            MyApp.updateLog(getCtx());
            finish();
        });

        binding.buttonToday.setOnClickListener(v -> checkSettingByNow());

        checkSettingByNow(); // 預設載入今天的日誌
    }

    private void checkSettingByNow() {
        loadLogsFromFile("debug.txt");
    }

    private void loadLogsFromFile(String fileName) {
        cancelLoading(); // 取消當前的加載任務
        resetReader();

        File txtDebug = new File(Tools.getExternalFilesDir(), fileName);

        if (txtDebug.exists()) {
            try (BufferedReader reader = new BufferedReader(new FileReader(txtDebug))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    buffer.addLast(line);
                }

                if (!buffer.isEmpty()) {
                    List<String> list = new ArrayList<>(buffer);
                    Collections.reverse(list);
                    buffer = new ArrayDeque<>(list);
                }
            } catch (IOException e) {
                getLogs().debug("讀取失敗: " + txtDebug + "，錯誤：" + e.getMessage());
            }
        }

        isEndOfFile = buffer.isEmpty();
        loadMoreLines();
    }

    private void loadLogsByDate(String date) {
        cancelLoading();
        resetReader();

        for (int index = 24; index >= 0; index--) {
            String strFileName = date + (index <= 9 ? "0" + index : String.valueOf(index)) + ".txt";
            File txtDebugByHH = new File(Tools.getExternalFilesDir(), strFileName);

            if (txtDebugByHH.exists()) {
                getLogs().debug("exists:" + txtDebugByHH.getAbsolutePath());

                try (BufferedReader reader = new BufferedReader(new FileReader(txtDebugByHH))) {
                    String line;
                    while ((line = reader.readLine()) != null) {
                        buffer.addLast(line);
                    }

                    if (!buffer.isEmpty()) {
                        List<String> list = new ArrayList<>(buffer);
                        Collections.reverse(list);
                        buffer = new ArrayDeque<>(list);
                    }
                } catch (IOException e) {
                    getLogs().debug("讀取失敗: " + strFileName + "，錯誤：" + e.getMessage());
                }
            }
        }

        isEndOfFile = buffer.isEmpty();
        loadMoreLines();
    }

    private void loadMoreLines() {
        if (isLoading || isEndOfFile) return;
        isLoading = true;

        loadingThread = new Thread(() -> {
            List<String> tempList = new ArrayList<>();

            for (int i = 0; i < BATCH_SIZE && !buffer.isEmpty(); i++) {
                tempList.add(buffer.removeFirst());
            }

            if (buffer.isEmpty() && tempList.isEmpty()) {
                isEndOfFile = true;
            }

            if (!tempList.isEmpty()) {
                runOnUiThread(() -> {
                    int startIndex = statusList.size();
                    statusList.addAll(tempList);
                    recyclerDebugAdpter.notifyItemRangeInserted(startIndex, tempList.size());
                    isLoading = false;
                });
            } else {
                isLoading = false;
            }
        });

        loadingThread.start();
    }

    private void resetReader() {
        buffer.clear();
        statusList.clear();
        recyclerDebugAdpter.notifyDataSetChanged();
        isLoading = false;
        isEndOfFile = false;
    }

    private void cancelLoading() {
        if (loadingThread != null && loadingThread.isAlive()) {
            loadingThread.interrupt(); // 停止當前的加載執行緒
        }
        isLoading = false;
    }
}