# -*- coding: utf-8 -*-
from core.utils.db import db
from core.utils.packages.session import BackupOnDeleteMixin
from sqlalchemy.orm import backref
from sqlalchemy import BigInteger
from datetime import datetime, timezone 
from sqlalchemy import desc, func, String, case, literal_column  
from sqlalchemy.ext.hybrid import hybrid_property 
from sqlalchemy.sql.expression import null 

class Location(db.Model, BackupOnDeleteMixin):
    __tablename__ = 'location'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(255))
    objectsQty = db.Column(db.Integer())
    parent_id = db.Column(db.Integer, db.ForeignKey('location.id', ondelete='SET NULL'), nullable=True)
    parent = db.relationship('Location', remote_side=[id], backref=db.backref('parent_childs'))
    position = db.Column(db.String(255))
    createdby_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    modifiedby_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    createdby = db.relationship('User', backref='created_locations', foreign_keys=[createdby_id])
    modifiedby = db.relationship('User', backref='modified_locations', foreign_keys=[modifiedby_id])
    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))

    def helper_objectsQty(self):
        from project.scripts.objectsQty import qty
        result = qty(self)
        self.objectsQty = result
        try:
            db.session.add(self) 
            db.session.commit() 
        except Exception as e:
            db.session.rollback()
            raise 
        return self.objectsQty

    @hybrid_property
    def full_repr(self):
        result = f'''{self.name if self.name is not None else ''} < {self.parent if self.parent is not None else ''}'''
        return result.strip()

    @full_repr.expression
    def full_repr(cls):
        return (
            literal_column("") + literal_column("''")  + func.coalesce(cls.name, literal_column("''"))  + literal_column("' <'") + literal_column("' '")  + func.coalesce(cls.parent, literal_column("''"))  + literal_column("''")
        )

    def __repr__(self) -> str:
        return self.full_repr 
    __default_ordering__ = [position]

    __table_args__ = {
        "mysql_charset": "utf8mb4",
        "mysql_collate": "utf8mb4_unicode_ci",
    }


def get_fields():
    fields = {'name': {'id': 194, 'type': 'String', 'name': 'name', 'maxlength': None, 'connected_table': None, 'label': 'Nombre', 'input': 'text', 'sort': None, 'required': False, 'hidden': False, 'publicBlob': False, 'default_value': None, 'select_options': None, 'extraclass': None, 'allowHtml': False, 'hasManyValues': False, 'readOnly': False, 'calculate_file': None, 'calculate_function': None, 'helper': None}, 'objectsQty': {'id': 195, 'type': 'Integer', 'name': 'objectsQty', 'maxlength': None, 'connected_table': None, 'label': 'Número de Objetos', 'input': 'number', 'sort': None, 'required': False, 'hidden': False, 'publicBlob': False, 'default_value': None, 'select_options': None, 'extraclass': None, 'allowHtml': False, 'hasManyValues': False, 'readOnly': True, 'calculate_file': 'objectsQty', 'calculate_function': 'qty', 'helper': 'script'}, 'parent': {'id': 196, 'type': 'selfParent', 'name': 'parent', 'maxlength': None, 'connected_table': 18, 'label': 'Pertenece a:', 'input': 'connected_table', 'sort': None, 'required': False, 'hidden': False, 'publicBlob': False, 'default_value': None, 'select_options': None, 'extraclass': None, 'allowHtml': False, 'hasManyValues': False, 'readOnly': False, 'calculate_file': None, 'calculate_function': None, 'helper': None}, 'position': {'id': 197, 'type': 'String', 'name': 'position', 'maxlength': None, 'connected_table': None, 'label': 'Ordenar', 'input': 'float', 'sort': None, 'required': False, 'hidden': False, 'publicBlob': False, 'default_value': None, 'select_options': None, 'extraclass': None, 'allowHtml': False, 'hasManyValues': False, 'readOnly': False, 'calculate_file': None, 'calculate_function': None, 'helper': None}}
    return fields


def get_relevants():
    relevants = {}
    return relevants
