from app.extensions import db
from datetime import datetime
import json

class ViewProfile(db.Model):
    __tablename__ = 'view_profiles'

    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
    name = db.Column(db.String(100), nullable=False)
    view_type = db.Column(db.String(50), default='lv')  # lv, aufmass, ...
    config_json = db.Column(db.Text, default='{}')
    is_default = db.Column(db.Boolean, default=False)
    erstellt_am = db.Column(db.DateTime, default=datetime.utcnow)

    def get_config(self):
        try:
            return json.loads(self.config_json or '{}')
        except (json.JSONDecodeError, TypeError):
            return {}

    def set_config(self, config):
        self.config_json = json.dumps(config)

    @staticmethod
    def get_default_config():
        return {
            'column_order': ['fav', 'drag', 'pos_nr', 'text', 'einheit', 'ep', 'aktion'],
            'column_widths': {'fav': 32, 'drag': 28, 'pos_nr': 90, 'text': 400, 'einheit': 60, 'ep': 80, 'aktion': 70},
            'column_visible': {'fav': True, 'drag': True, 'pos_nr': True, 'text': True, 'einheit': True, 'ep': True, 'aktion': True},
        }

    def __repr__(self):
        return f'<ViewProfile {self.name} ({self.view_type})>'
