from database.database import db

class TrainingProject(db.Model):
    __tablename__ = 'training_project'
    
    project_id = db.Column(db.Integer, primary_key=True, unique=True, autoincrement=True)
    title = db.Column(db.String(255), nullable=False)
    description = db.Column(db.String(500))
    project_image = db.Column(db.LargeBinary)
    project_image_type = db.Column(db.String(100))
    
    # Relationship to classes (3NF)
    classes_relation = db.relationship('ProjectClass', backref='project', lazy=True, cascade='all, delete-orphan')
    
    def to_dict(self, include_classes=True):
        result = {
            'project_id': self.project_id,
            'title': self.title,
            'description': self.description,
            'project_image_type': self.project_image_type
        }
        
        # Include classes as array for backwards compatibility
        if include_classes:
            from models.ProjectClass import ProjectClass
            classes = ProjectClass.query.filter_by(project_id=self.project_id).order_by(ProjectClass.display_order).all()
            result['classes'] = [c.class_name for c in classes]
        
        if self.project_image:
            import base64
            base64_data = base64.b64encode(self.project_image).decode('utf-8')
            mime_type = self.project_image_type or 'image/png'
            result['project_image'] = f'data:{mime_type};base64,{base64_data}'
        else:
            result['project_image'] = None
        return result
