from PySide6.QtCore import QObject, Signal
from pypos.core.base_controller import BaseController
from pypos.modules.sinkronisasi.controllers.sync_flow_controller import SyncFlowController


class SinkronPenjualanController(BaseController, QObject):
    progress = Signal(str)
    selesai = Signal(str)

    def __init__(self, view=None):
        BaseController.__init__(self)
        QObject.__init__(self)
        self.view = view

        self.sync_flow = SyncFlowController(mode="manual", view=None, user_info=None, app_controller=None)
        self.sync_flow.sync_progress.connect(self._on_progress)
        self.sync_flow.sync_completed_rows.connect(self._on_finished)
        self.sync_flow.sync_failed_detail.connect(self._on_failed)

    def mulai_sinkron(self):
        if self.sync_flow.is_running():
            self.progress.emit("Sinkronisasi sedang berjalan, mohon tunggu...")
            return

        self.progress.emit("Memulai sinkronisasi data via API...")
        self.sync_flow.start()

    def _on_progress(self, percent, status, detail_log):
        self.progress.emit(f"{percent}% - {status}: {detail_log}")

    def _on_finished(self, total_rows):
        self.selesai.emit(f"Sinkronisasi selesai. Total {total_rows} data diperbarui.")

    def _on_failed(self, error_message):
        self.selesai.emit(f"Gagal sinkronisasi: {error_message}")

    def stop(self, force=False, wait_timeout_ms=None):
        self.sync_flow.stop(force=force, wait_timeout_ms=wait_timeout_ms)
