# coding: utf-8
from sqlalchemy import Column, DateTime, ForeignKey, Integer, String
from sqlalchemy.orm import relationship
from sqlalchemy.ext.declarative import declarative_base

import protopy.mod_satellite_pb2 as mod_satellite_pb

Base = declarative_base()
metadata = Base.metadata


# 增加 to_dict() 方法到 Base 类中
def to_dict(self):
    return {c.name: getattr(self, c.name, None)
            for c in self.__table__.columns}


# 将对象可以转化为 dict 类型
Base.to_dict = to_dict


class Satellite(Base):
    __tablename__ = 'satellite'

    norad = Column(String(5), primary_key=True)
    cn_name = Column(String(50))
    en_name = Column(String(50))
    base = Column(String(500))
    element = Column(String(500))
    create_time = Column(DateTime, comment='创建时间')

    def getPK(self):
        return ['norad']

    def to_proto(self):
        ret = mod_satellite_pb.RetSatelliteElement()
        if self.norad is not None: ret.norad = self.norad
        if self.cn_name is not None: ret.cnName = self.cn_name
        if self.en_name is not None: ret.enName = self.en_name
        return ret

    def back_proto(self, ret: mod_satellite_pb.RetSatelliteElement):
        self.norad = ret.norad
        self.cn_name = ret.cnName
        self.en_name = ret.enName


class SatelliteWork(Base):
    __tablename__ = 'satellite_work'

    norad = Column(ForeignKey('satellite.norad', ondelete='CASCADE'), primary_key=True, nullable=False)  # 级联删除
    config_id = Column(Integer, primary_key=True, nullable=False)
    remark = Column(String(50))
    config_name = Column(String(50))
    params = Column(String(500))
    create_time = Column(DateTime, comment='创建时间')

    satellite = relationship('Satellite')

    def getPK(self):
        return ['norad', 'config_id']
