from typing import Optional

from program_public_tools import ProgramPublicTools
from instrument_controller import InstrumentController
from serial_device_controller import SerialDeviceController
from powerline_adapter import PowerlineAdapter
from local_file_service import LocalFileService


class ProgramCore(object):
    def __init__(self, pubtools: Optional[ProgramPublicTools]):
        if pubtools is None:
            pubtools = ProgramPublicTools()
        self.pubtools: ProgramPublicTools = pubtools
        self.serial_controller: SerialDeviceController = SerialDeviceController(self.pubtools)
        self.powerline_adapter: PowerlineAdapter = PowerlineAdapter(self.pubtools)
        self.local_file_service: LocalFileService = LocalFileService()
        self.start_core()
        self.instrument_controller: InstrumentController = InstrumentController(self.pubtools)
        self.instrument_controller.auto_connect()
        if self.instrument_controller.services.digital_oscilloscope is not None:
            self.instrument_controller.services.digital_oscilloscope.keep_listening()
        if self.instrument_controller.services.digital_multimeter is not None:
            self.instrument_controller.services.digital_multimeter.keep_listening()

    def start_core(self):
        self.local_file_service.start()
        self.auto_connect()

    def auto_connect(self):
        self.serial_controller.auto_connect()
        self.powerline_adapter.init()
        self.local_file_service.start()
