# Generated by sila2.code_generator; sila2.__version__: 0.12.2
from __future__ import annotations

import string
from typing import TYPE_CHECKING

from opentrons.protocol_api import ProtocolContext, Labware
from sila2.server import MetadataDict

from ..generated.sessionmanagement import (
    MovePlateToTest_Responses,
    RegisterPlate_Responses,
    SessionCreate_Responses,
    SessionDelete_Responses,
    SessionManagementBase,
)

if TYPE_CHECKING:
    from ..server import Server

import opentrons.execute
import uuid

lol: string = None
protocol: ProtocolContext | None = None
plate: Labware | None = None


class SessionManagementImpl(SessionManagementBase):
    def __init__(self, parent_server: Server) -> None:
        super().__init__(parent_server=parent_server)

    def SessionCreate(self, *,
                      metadata: MetadataDict) -> SessionCreate_Responses:
        global lol
        global protocol
        if lol is None:
            lol = str(uuid.uuid4())
            protocol = opentrons.execute.get_protocol_api("2.19")
            protocol.home()
            return SessionCreate_Responses(SessionToken=lol)

        raise "Machine is already in use"

    def SessionDelete(self, SessionToken: str, *,
                      metadata: MetadataDict) -> SessionDelete_Responses:
        global lol
        global protocol
        if SessionToken == lol:
            protocol.cleanup()
            protocol = None
            lol = None

        return SessionDelete_Responses()

    def RegisterPlate(self, Position: str, *,
                      metadata: MetadataDict) -> RegisterPlate_Responses:
        global protocol
        global plate

        if protocol is not None:
            # Loading should be done in seperate method but this is fine for testing
            plate = protocol.load_labware("corning_96_wellplate_360ul_flat",
                                          "D1")
            return RegisterPlate_Responses()

        raise "No protocol found"

    def MovePlateToTest(self, Position: str, *,
                        metadata: MetadataDict) -> MovePlateToTest_Responses:
        global protocol
        global plate

        if protocol is not None:
            protocol.home()
            plate = protocol.load_labware("corning_96_wellplate_360ul_flat",
                                          "D1")
            protocol.move_labware(plate, Position)
            protocol.move_labware(plate, "D1")
            return MovePlateToTest_Responses()

        raise "No protocol found"
