"""
Yeastar Models - GMAO Collège
Surveillance téléphone P520
"""
from datetime import datetime, timezone
from app_new.extensions import db
from cryptography.fernet import Fernet
import os


class YeastarConfig(db.Model):
    """Identifiants de connexion Yeastar P520."""
    __tablename__ = "yeastar_config"
    __table_args__ = {'extend_existing': True}
    
    id = db.Column(db.Integer, primary_key=True)
    base_url = db.Column(db.String(500), nullable=False)
    username_encrypted = db.Column(db.LargeBinary, nullable=False)
    password_encrypted = db.Column(db.LargeBinary, nullable=False)
    is_active = db.Column(db.Boolean, default=True)
    created_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc))
    updated_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc), onupdate=lambda: datetime.now(timezone.utc))
    
    # Clé de chiffrement (stockée en variable d'environnement ou générée)
    @staticmethod
    def _get_fernet():
        """Construit Fernet avec une clé persistante fournie par l'environnement."""
        key = os.environ.get('YEASTAR_ENCRYPTION_KEY') or os.environ.get(
            'OUTLOOK_ENCRYPTION_KEY'
        )
        if not key:
            raise RuntimeError(
                'YEASTAR_ENCRYPTION_KEY ou OUTLOOK_ENCRYPTION_KEY doit etre configuree'
            )
        return Fernet(key.encode() if isinstance(key, str) else key)
    
    def set_password(self, password):
        """Chiffre et stocke le mot de passe."""
        self.password_encrypted = self._get_fernet().encrypt(password.encode())
    
    def get_password(self):
        """Déchiffre et retourne le mot de passe."""
        if not self.password_encrypted:
            return None
        return self._get_fernet().decrypt(self.password_encrypted).decode()
    
    def set_username(self, username):
        """Chiffre et stocke le nom d'utilisateur."""
        self.username_encrypted = self._get_fernet().encrypt(username.encode())
    
    def get_username(self):
        """Déchiffre et retourne le nom d'utilisateur."""
        if not self.username_encrypted:
            return None
        return self._get_fernet().decrypt(self.username_encrypted).decode()
    
    @staticmethod
    def get_config():
        """Récupère la configuration active."""
        return YeastarConfig.query.filter_by(is_active=True).first()
    
    def __repr__(self):
        return f"<YeastarConfig {self.base_url}>"


class YeastarDNDConfig(db.Model):
    """Configuration du watchdog DND pour Yeastar P520."""
    __tablename__ = "yeastar_dnd_config"
    __table_args__ = {'extend_existing': True}
    
    id = db.Column(db.Integer, primary_key=True)
    is_enabled = db.Column(db.Boolean, default=False)
    refresh_seconds = db.Column(db.Integer, default=1)
    reset_delay_seconds = db.Column(db.Integer, default=3)
    excluded_extensions = db.Column(db.Text, default="100,111")  # IDs séparés par virgule
    created_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc))
    updated_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc), onupdate=lambda: datetime.now(timezone.utc))
    
    @property
    def excluded_list(self):
        """Retourne la liste des extensions exclues."""
        return [e.strip() for e in (self.excluded_extensions or '').split(',') if e.strip()]
    
    def get(self, key, default=None):
        """Methode get pour compatibilite template dict-like."""
        return getattr(self, key, default)
    
    def __repr__(self):
        return f"<YeastarDNDConfig enabled={self.is_enabled}>"
