from sqlalchemy import Column, Integer, ForeignKey
from sqlalchemy.orm import relationship, backref
from helix.models.sql.inverters import Inverter
from helix.models.sql.power_stations import PowerStation
from helix.models.sql.shared_sql_base import Base


class StandaloneInverter(Base):
    __tablename__ = 'standalone_inverters'
    id = Column(Integer, primary_key=True)
    site_id = Column(Integer, ForeignKey('sites.id'))
    ac_run_length = Column(Integer, nullable=False)
    inverter = relationship(Inverter.__name__,
                            backref=backref("standalone_inverters", uselist=False),
                            cascade="save-update, merge, delete")
    attachment_point_id = Column(Integer, ForeignKey('power_stations.id'))
    attachment_point = relationship(PowerStation.__name__)


    def to_json(self):
        if self.attachment_point:
            attachment_point = (self.attachment_point.description, self.attachment_point.id)
        else:
            attachment_point = ('Switch Gear', None)
        return { **{
            'standalone_inverter_id': self.id,
            'ac_run_length': self.ac_run_length,
            'attachment_point': attachment_point
        }, **(self.inverter[0].to_json()) }
