''' Module for Starting a Measurement '''
import logging

# pylint: disable=no-name-in-module, wrong-import-position, import-error
# noqa: E402
from qgis.core import (  # noqa: E402
    QgsVectorLayer,
)
from PyQt5.QtWidgets import QMessageBox
from ..logger import Logger  # noqa: E402
from ..logger import log  # noqa: E402
from ..street_smart import AbstractCommand  # noqa: E402

logger = Logger(__name__).get()


class CreateMeasureCommand(AbstractCommand):
    '''
    Class for Create Measure Command
    '''
    def __init__(self, iface, streetsmart):
        '''
        Constructor
        '''
        super().__init__(iface, streetsmart)
        super().set_disabled()
        self.is_checked = False
        self.streetsmart.buttonstate.panorama_viewer_opened.connect(
            self.set_enabled)
        self.streetsmart.buttonstate.panorama_viewer_closed.connect(
            self.on_panorama_viewer_closed)

    @log(logging.DEBUG)
    def on_panorama_viewer_closed(self):
        """ Called when panorama viewer is closed - uncheck toggle and disable button """
        # Stop measurement if it was active
        if self.is_checked:
            self.is_checked = False
            action = self.action
            if action:
                action.setChecked(False)
            # Send stop measure command
            self.streetsmart.sendToViewer("stopmeasure")
            # Disconnect layer change listener
            try:
                self.iface.currentLayerChanged.disconnect(
                    self.streetsmart.current_layer_changed)
            except Exception:  # nosec B110 - signal may already be disconnected
                pass  # Already disconnected
        # Disable the button
        self.set_disabled()

    @staticmethod
    def icon_path():
        '''
        Path for the icon
        '''
        return ':/plugins/street_smart/resources/mActionAllEdits.svg'

    def text(self):
        '''
        Text for the command to show
        '''
        return super().tr("Start Measure")

    def parent(self):
        '''
        Parent
        '''
        return self.iface.mainWindow()

    # TODO: create a checkedabstractcommand and move this code into it. This
    # command and add_overlay_command both are childeren.
    def __set_action_state(self):
        """ Toggles the state of the action """
        action = self.action
        if action:
            action.setCheckable(True)
            action.setChecked(not self.is_checked)
            self.is_checked = not self.is_checked

    def callback(self):
        '''
        Code to execute when command is clicked
        '''
        # If turning OFF measurement - just toggle and send stop command
        if self.is_checked:
            self.__set_action_state()
            self.streetsmart.sendToViewer("stopmeasure")
            try:
                self.iface.currentLayerChanged.disconnect(
                    self.streetsmart.current_layer_changed)
            except Exception:  # nosec B110 - signal may already be disconnected
                pass  # Already disconnected
            return

        # TURNING ON measurement - perform checks first
        # Check 1: Is panorama viewer open?
        cone = self.streetsmart.buttonstate.previous_cone
        if cone is None or cone.cone is None:
            QMessageBox.information(
                None,
                "Panorama Viewer Not Started",
                "Please start the Panorama Viewer first by clicking on a point in the map."
            )
            return

        # Check 2: Is there an active layer?
        active_layer = self.iface.activeLayer()
        if not isinstance(active_layer, QgsVectorLayer):
            QMessageBox.information(
                None,
                "No Vector Layer Selected",
                "Please select a vector layer in the Layers panel to store measurements."
            )
            return

        # Check 3: Is the layer editable? If not, automatically enable editing
        if not active_layer.isEditable():
            # Automatically start editing
            if active_layer.startEditing():
                logger.info(f"Automatically enabled editing for layer: {active_layer.name()}")
            else:
                QMessageBox.warning(
                    None,
                    "Cannot Enable Editing",
                    f"Could not enable editing for layer '{active_layer.name()}'.\n\n"
                    "Please check layer permissions and try again."
                )
                return

        # All checks passed - toggle state and start measurement
        self.__set_action_state()
        feature_type = self.streetsmart.get_vectorlayer_feature_type(active_layer)
        self.__send_start_measure(feature_type)
        self.iface.currentLayerChanged.connect(
            self.streetsmart.current_layer_changed)

    @log(logging.DEBUG)
    def __send_start_measure(self, measure_type):
        '''
        Send measure message to Panorama Viewer
        '''
        msg = "startmeasure|" + measure_type
        self.streetsmart.sendToViewer(msg)
