# servercontext.py

from pathlib import Path
from threading import Lock

from plotink import ebb_serial

from . import ut
from .axicontroller import AxiController


class ServerContext:
    def __init__(
        self,
        ad: AxiController,
        file_root: Path,
        srv_opts_path: str,
        log_filename: Path,
        plot_status_log_filename: Path,
    ):
        self.ad = ad
        self.ebb_serial = ebb_serial
        self.file_root = file_root
        self.srv_opts_path = srv_opts_path
        self.log_filename = log_filename
        self.plot_status_log_filename = plot_status_log_filename
        self.ad_lock = Lock()
        self.plot_state_lock = Lock()
        self.paused_job_lock = Lock()
        self.plot_in_progress = False
        self.plot_thread = None
        self.paused_job = None
        self.plot_state = {
            'status': 'idle',
            'message': '',
            'error': '',
            'current_layer': 0,
            'total_layers': 0,
            'progress_mm': 0.0,
            'progress_raw_mm': None,
            'total_mm': 0.0,
            'started_at': None,
            'finished_at': None,
            'resume_available': False,
            'paused_layer': None,
            'paused_layer_path': None,
        }
        self.srv_options = ut.load_srv_options(srv_opts_path)
        self.ad.apply_srv_options(self.srv_options)

    def update_plot_state(self, **kwargs) -> None:
        with self.plot_state_lock:
            self.plot_state.update(kwargs)

    def set_paused_job(self, job) -> None:
        with self.paused_job_lock:
            self.paused_job = job

    def get_paused_job(self):
        with self.paused_job_lock:
            return self.paused_job

    def get_existing_total(self) -> float:
        with self.plot_state_lock:
            return float(self.plot_state.get('total_mm') or 0.0)
