import datetime

from sqlalchemy import Boolean, Column, Date, DateTime, ForeignKey, Integer, String

from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base

from sqlalchemy.orm import relationship, sessionmaker

from slugify import slugify


#engine = create_engine('sqlite:///:memory:', echo=True)
engine = create_engine('sqlite:///impax.db', echo=False)
#engine = create_engine('sqlite:////dev/shm/test.db', echo=True)


Base = declarative_base()

'''
['Group', 'View', 
'patient.patient_id', 'patient.patient_name', 'patient.patient_name_ph_utf8', 
'study.accession_number', 'study.date_time_created', 'study.modality', 'study.num_images', 'study.status', 'study.study_date', 'study.study_description', 'study.study_time']
'''


class Patient(Base):
    __tablename__ = 'patient'

    patient_id           = Column(String, primary_key=True)
    patient_name         = Column(String)
    patient_name_ph_utf8 = Column(String)

    counter = Column(Integer)

    created = Column(DateTime, default=datetime.datetime.now)
    saved   = Column(DateTime, onupdate=datetime.datetime.now)

    studies = relationship("Study")



class Study(Base):
    __tablename__ = 'study'

    accession_number  = Column(String, primary_key=True)
    date_time_created = Column(String)
    modality          = Column(String)
    num_images        = Column(Integer)
    status            = Column(String)
    study_date        = Column(Date)
    study_description = Column(String)
    study_time        = Column(String)

    report            = Column(String)

    run               = Column(String)
    success           = Column(Boolean)

    patient_id = Column(String, ForeignKey('patient.patient_id'))

    created = Column(DateTime, default=datetime.datetime.now)
    saved   = Column(DateTime, onupdate=datetime.datetime.now)

    def naming(self):
        return f'{self.study_date}_{self.modality}_{self.accession_number}'


class Series(Base):
    __tablename__ = 'series'

    series_uid   = Column(String, primary_key=True)
    name         = Column(String)

    document0    = Column(String)
    document1    = Column(String)

    accession_number = Column(String, ForeignKey('study.accession_number'))

    created = Column(DateTime, default=datetime.datetime.now)
    saved   = Column(DateTime, onupdate=datetime.datetime.now)

    def slugify(self):
        return slugify(self.name)


Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
