from sqlalchemy import Column, Integer, Enum, Boolean, ForeignKey, CheckConstraint
from helix.constants.inverter_type import InverterType
from helix.models.sql.shared_sql_base import Base


class Inverter(Base):
    __tablename__ = 'inverters'
    id = Column(Integer, primary_key=True)
    model = Column(Enum(*map(lambda x: str(x.value), InverterType.all()), name='invertertype'), nullable=False)
    strings_per_inverter = Column(Integer, nullable=False)
    sunshade = Column(Boolean)
    dc_switch = Column(Boolean)
    splice_box = Column(Boolean)
    power_station_id = Column(Integer, ForeignKey('power_stations.id'))
    standalone_inverter_id = Column(Integer, ForeignKey('standalone_inverters.id', ondelete='CASCADE'))

    __table_args__ = (
        CheckConstraint('(power_station_id IS NULL != standalone_inverter_id IS NULL)'),
    )

    def to_json(self):
        inverter_type = InverterType.SMA if int(self.model) in InverterType.SMA.all() else InverterType.DELTA
        return {
            'model': inverter_type(int(self.model)),
            'strings_per_inverter': self.strings_per_inverter,
            'sunshade': self.sunshade,
            'dc_switch': self.dc_switch,
            'splice_box': self.splice_box,
        }
