import time

# edited by glg


class DashboardWindowUiService:
    @staticmethod
    def build_sync_status_payload(needs_sync):
        if bool(needs_sync):
            return {
                "text": "\u26a0\ufe0f Data Perlu Sinkronisasi",
                "style": "color: orange; font-weight: bold; font-size: 14px;",
                "show_button": True,
            }
        return {
            "text": "\u2705 Data Up-to-date",
            "style": "color: green; font-weight: bold; font-size: 14px;",
            "show_button": False,
        }

    @staticmethod
    def format_row_count(value):
        try:
            parsed = int(value or 0)
        except (TypeError, ValueError, KeyError, AttributeError, RuntimeError, OSError, LookupError, ArithmeticError, ImportError):
            parsed = 0
        return f"{max(0, parsed):,}".replace(",", ".")

    @staticmethod
    def elapsed_ms(started_at, now_value=None):
        now = float(now_value) if now_value is not None else float(time.perf_counter())
        try:
            started = float(started_at)
        except (TypeError, ValueError, KeyError, AttributeError, RuntimeError, OSError, LookupError, ArithmeticError, ImportError):
            started = now
        return max(0.0, (now - started) * 1000.0)

    @staticmethod
    def build_perf_log_message(label, elapsed_ms, extra=""):
        message = f"[PERF] {str(label or '-')} elapsed_ms={float(elapsed_ms):.1f}"
        if extra:
            message = f"{message} {str(extra)}"
        return message

    @staticmethod
    def should_log_info(elapsed_ms, threshold_ms=180.0, always_info=False):
        return bool(always_info) or float(elapsed_ms or 0.0) >= float(threshold_ms or 0.0)

    @staticmethod
    def build_auto_sync_feedback_payload(total_rows):
        try:
            rows = int(total_rows or 0)
        except (TypeError, ValueError, KeyError, AttributeError, RuntimeError, OSError, LookupError, ArithmeticError, ImportError):
            rows = 0
        if rows <= 0:
            return None

        rows_text = DashboardWindowUiService.format_row_count(rows)
        return {
            "rows": rows,
            "rows_text": rows_text,
            "status_text": f"Data terbaru siap dipakai ({rows_text} data diperbarui).",
            "toast_text": (
                "Sinkronisasi otomatis selesai. "
                f"Data baru berhasil diperbarui: {rows_text} baris."
            ),
            "toast_duration_ms": 3600,
            "clear_delay_ms": 9000,
        }
