"""Agendador da sincronizacao periodica com o Geotab e da checagem de licença online."""
from datetime import datetime, timezone
from apscheduler.schedulers.background import BackgroundScheduler

from . import security, license_online
from .sync_service import run_sync

_scheduler = BackgroundScheduler()
_SYNC_JOB_ID = "geotab_sync"
_LICENSE_JOB_ID = "license_check"
LICENSE_CHECK_INTERVAL_MINUTES = 60
STATUS_CHECK_INTERVAL_MINUTES = 5


def _sync_job():
    if security.load_active_license() and security.has_geotab_credentials():
        run_sync()


def _license_job():
    license_online.refresh_from_server()


def _status_job():
    """A cada 5 min: se servidor marcar bloqueado, cria flag local que bloqueia o app na proxima request."""
    license_online.apply_server_status()


def start_scheduler():
    if _scheduler.running:
        return
    interval = security.load_settings()["sync_interval_minutes"]
    _scheduler.add_job(_sync_job, "interval", minutes=interval, id=_SYNC_JOB_ID)
    _scheduler.add_job(_license_job, "interval", minutes=LICENSE_CHECK_INTERVAL_MINUTES, id=_LICENSE_JOB_ID)
    _scheduler.add_job(_status_job, "interval", minutes=STATUS_CHECK_INTERVAL_MINUTES, id="status_check",
                       next_run_time=datetime.now(timezone.utc))
    _scheduler.start()


def reschedule(interval_minutes: int):
    if _scheduler.get_job(_SYNC_JOB_ID):
        _scheduler.reschedule_job(_SYNC_JOB_ID, trigger="interval", minutes=interval_minutes)


def shutdown_scheduler():
    if _scheduler.running:
        _scheduler.shutdown(wait=False)
