from enum import Enum as PyEnum

from sqlalchemy import Column, DateTime, String, Integer, text
from sqlalchemy.dialects.postgresql import ENUM as SqlEnum
from sqlalchemy.orm import relationship

from load.projects.cloud.loadtesting.db.connection import BASE


class ClientStatus(PyEnum):
    STATUS_UNSPECIFIED = 'STATUS_UNSPECIFIED'
    PREPARING_TEST = 'PREPARING_TEST'
    READY_FOR_TEST = 'READY_FOR_TEST'
    TESTING = 'TESTING'
    TANK_FAILED = 'TANK_FAILED'


class Status(PyEnum):
    STATUS_UNSPECIFIED = 'STATUS_UNSPECIFIED'
    PREPARING_TEST = 'PREPARING_TEST'
    READY_FOR_TEST = 'READY_FOR_TEST'
    TESTING = 'TESTING'
    TANK_FAILED = 'TANK_FAILED'
    PROVISIONING = 'PROVISIONING'
    STOPPING = 'STOPPING'
    STOPPED = 'STOPPED'
    STARTING = 'STARTING'
    RESTARTING = 'RESTARTING'
    UPDATING = 'UPDATING'
    ERROR = 'ERROR'
    CRASHED = 'CRASHED'
    DELETING = 'DELETING'
    LOST_CONNECTION_WITH_TANK = 'LOST_CONNECTION_WITH_TANK'
    INITIALIZING_CONNECTION = 'INITIALIZING_CONNECTION'


class TankTable(BASE):
    __tablename__ = 'tanks'
    n = Column('n', Integer(), primary_key=True, autoincrement=True)
    id = Column('id', String(50), unique=True)
    compute_instance_id = Column('compute_instance_id', String(50), unique=True)
    client_status = Column('client_status',
                           SqlEnum(*[s.value for s in Status], name='client_statuses_enum'))
    status = Column('status',
                    SqlEnum(*[s.value for s in Status], name='statuses_enum'))
    client_updated_at = Column('client_updated_at', DateTime)
    folder_id = Column('folder_id', String(50))
    tank_folder_id = Column('tank_folder_id', String(50))
    created_at = Column('created_at', DateTime, nullable=False, server_default=text("now()"))
    compute_instance_updated_at = Column('compute_instance_updated_at', DateTime)
    description = Column('description', String(256))
    service_account_id = Column('service_account_id', String(50))
    preset_id = Column('preset_id', String(50))
    tank_version = Column('tank_version', String(50))
    errors = Column('errors', String(50))
    name = Column('name', String(50))
    labels = Column('labels', String(50))
    current_job = Column('current_job', String(50))
    # agent_version is image_id
    agent_version = Column('agent_version', String())

    jobs = relationship('JobTable', back_populates='tank')

    def __str__(self):
        return f"Tank instance {self.id}, {self.client_status}"
