from itsdangerous import URLSafeTimedSerializer as Serializer
from datetime import datetime
from minibase import db, login_manager
from flask_login import UserMixin
from flask import current_app


@login_manager.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))


class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(20), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)
    image_file = db.Column(db.String(20), nullable=False, default='default.jpg')
    password = db.Column(db.String(60), nullable=False)
    # Additional Querry to link a post wiht an author in the sql this won't be an field
    posts = db.relationship('Post', backref='author', lazy=True)

    def get_reset_token(self, expires_sec=1800):
        s = Serializer(current_app.config['SECRET_KEY'], expires_sec)
        return s.dumps({'user_id': self.id}).decode('utf-8')

    @staticmethod
    def verify_reset_token(token):
        s = Serializer(current_app.config['SECRET_KEY'])
        try:
            user_id = s.loads(token)['user_id']
        except:
            return 0
        return User.query.get(user_id)

    # returns a more information-rich, or official, string representation of an object
    def __repr__(self):
        return f"User('{self.username}', '{self.email}', '{self.image_file}')"


class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(100), nullable=False)

    date_posted = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
    content = db.Column(db.Text, nullable=False)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)

    # returns a more information-rich, or official, string representation of an object
    def __repr__(self):
        return f"User('{self.title}', '{self.date_posted}')"

###################################################################################################
# ADMIN
###################################################################################################
class Country(db.Model):
    id = db.Column(db.Integer, nullable=False, primary_key=True)
    name = db.Column(db.String(100), nullable=False)
    iso3 = db.Column(db.String(3), nullable=True)
    numeric_code = db.Column(db.String(3), nullable=True)
    iso2 = db.Column(db.String(2), nullable=True)
    phonecode = db.Column(db.String(255), nullable=True)
    capital = db.Column(db.String(255), nullable=True)
    currency = db.Column(db.String(255), nullable=True)
    currency_name = db.Column(db.String(255), nullable=True)
    currency_symbol = db.Column(db.String(255), nullable=True)
    tld = db.Column(db.String(255), nullable=True)
    native = db.Column(db.String(255), nullable=True)
    region = db.Column(db.String(255), nullable=True)
    region_id = db.Column(db.Integer, nullable=True)
    subregion = db.Column(db.String(255), nullable=True)
    subregion_id = db.Column(db.Integer, nullable=True)
    nationality = db.Column(db.String(255), nullable=True)
    timezones = db.Column(db.String(255), nullable=True)
    translations = db.Column(db.String(255), nullable=True)
    latitude = db.Column(db.Float, nullable=True)
    longitude = db.Column(db.Float, nullable=True)
    emoji = db.Column(db.String(191), nullable=True)
    emojiU = db.Column(db.String(191), nullable=True)
    created_at = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, nullable=False, default=datetime.utcnow, onupdate=datetime.utcnow)
    flag = db.Column(db.Integer, nullable=False, default=1)
    wikiDataId = db.Column(db.String(255))

    companies = db.relationship('Company', backref='company_country', viewonly=True, lazy=True)
    prodution_land = db.relationship('Product', backref='product_country_production', viewonly=True, lazy=True)
    persons = db.relationship('Person', backref='person_country', viewonly=True, lazy=True)

    # returns a more information-rich, or official, string representation of an object
    def __repr__(self):
        return f"{self.name}"


class Status(db.Model):
    id = db.Column(db.Integer, nullable=False, primary_key=True)
    name = db.Column(db.String(50), nullable=False)
    description = db.Column(db.String(300), nullable=False)
    upload_date = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
    last_update_date = db.Column(db.DateTime, nullable=False, default=datetime.utcnow, onupdate=datetime.utcnow)

    # returns a more information-rich, or official, string representation of an object
    def __repr__(self):
        return f"{self.name}"


class Note_status(db.Model):
    id = db.Column(db.Integer, nullable=False, primary_key=True)
    name = db.Column(db.String(50), nullable=False)
    description = db.Column(db.String(300), nullable=False)
    upload_date = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
    last_update_date = db.Column(db.DateTime, nullable=False, default=datetime.utcnow, onupdate=datetime.utcnow)
    company_notes = db.relationship('Company_note', backref='company_note_status', lazy=True)
    person_notes = db.relationship('Person_note', backref='person_note_status', lazy=True)
    project_notes = db.relationship('Project_note', backref='project_note_status', lazy=True)

    # returns a more information-rich, or official, string representation of an object
    def __repr__(self):
        return f"{self.name}"

class Company_status(db.Model):
    id = db.Column(db.Integer, nullable=False, primary_key=True)
    name = db.Column(db.String(50), nullable=False)
    description = db.Column(db.String(300), nullable=False)
    upload_date = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
    last_update_date = db.Column(db.DateTime, nullable=False, default=datetime.utcnow, onupdate=datetime.utcnow)
    companies = db.relationship('Company', backref='status', lazy=True)

    # returns a more information-rich, or official, string representation of an object
    def __repr__(self):
        return f"{self.name}"


class Industry(db.Model):
    id = db.Column(db.Integer, nullable=False, primary_key=True)
    name = db.Column(db.String(50), nullable=False)
    description = db.Column(db.String(300), nullable=False)
    upload_date = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
    last_update_date = db.Column(db.DateTime, nullable=False, default=datetime.utcnow, onupdate=datetime.utcnow)
    companies = db.relationship('Company', backref='company_industry', lazy=True)
    projects = db.relationship('Project', backref='project_industry', lazy=True)

    # returns a more information-rich, or official, string representation of an object
    def __repr__(self):
        return f"{self.name}"


###################################################################################################
# Person
###################################################################################################
class Person(db.Model):
    id = db.Column(db.Integer, nullable=False, primary_key=True)
    name = db.Column(db.String(50), nullable=False)
    last_name = db.Column(db.String(50), nullable=False)
    date_of_birth = db.Column(db.Date, nullable=True, default=datetime.utcnow)
    mail_prof = db.Column(db.String(320), nullable=False)
    mail_priv = db.Column(db.String(320), nullable=True, default='')
    tel_prof_fix = db.Column(db.String(30), nullable=True, default='')
    tel_prof_mobile = db.Column(db.String(30), nullable=True, default='')
    tel_priv_fix = db.Column(db.String(30), nullable=True, default='')
    tel_priv_mobile = db.Column(db.String(30), nullable=True, default='')
    street_name = db.Column(db.String(150), nullable=True, default='')
    street_no = db.Column(db.Integer, nullable=True, default='')
    city = db.Column(db.String(75), nullable=True, default='')
    post_code = db.Column(db.String(10), nullable=True, default='')
    state = db.Column(db.String(75), nullable=True, default='')
    country_id = db.Column(db.Integer, db.ForeignKey('country.id'), nullable=False)
    image_file = db.Column(db.String(20), nullable=False, default='default_person.jpg')
    upload_date = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
    last_update_date = db.Column(db.DateTime, nullable=False, default=datetime.utcnow, onupdate=datetime.utcnow)

    # One To Many relationships where indexes can point o mutiple companies.
    # Example : One Legal_entity could cocern multiple companies. (There are surely more than just one GmBH)
    company_id = db.Column(db.Integer, db.ForeignKey('company.id'), nullable=False)
    role_id = db.Column(db.Integer, db.ForeignKey('person_role.id'), nullable=False)
    competence_id = db.Column(db.Integer, db.ForeignKey('person_competence.id'), nullable=False)

    # One To Many relationships for a company having mutliple elements of the following indexes
    # Example : One company would/could have many eployees
    notes = db.relationship('Person_note', backref='person', lazy=True)
    projects = db.relationship('Project', backref='project_responsible', lazy=True, viewonly=True)
    elements = db.relationship('Project', backref='element_responsible', lazy=True, viewonly=True)

    def __repr__(self):
        return f"{self.name} {' '} {self.last_name}"


class Person_role(db.Model):
    id = db.Column(db.Integer, nullable=False, primary_key=True)
    name = db.Column(db.String(50), nullable=False)
    description = db.Column(db.String(300), nullable=False)
    persons = db.relationship('Person', backref='role', lazy=True)

    # returns a more information-rich, or official, string representation of an object
    def __repr__(self):
        return f"{self.name}"


class Person_competence(db.Model):
    id = db.Column(db.Integer, nullable=False, primary_key=True)
    name = db.Column(db.String(50), nullable=False)
    description = db.Column(db.String(300), nullable=False)
    persons = db.relationship('Person', backref='competence', lazy=True)

    # returns a more information-rich, or official, string representation of an object
    def __repr__(self):
        return f"{self.name}"


class Person_note(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    priority = db.Column(db.Integer, nullable=False, default='0')
    title = db.Column(db.String(100), nullable=False)
    content = db.Column(db.Text, nullable=False)
    date_posted = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
    date_due = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)

    person_id = db.Column(db.Integer, db.ForeignKey('person.id'), nullable=False)
    status_id = db.Column(db.Integer, db.ForeignKey('note_status.id'), nullable=False)

    # returns a more information-rich, or official, string representation of an object
    def __repr__(self):
        return f"{self.title}, {self.status}, {self.content}"


###################################################################################################
# Company
###################################################################################################
class Company(db.Model):
    id = db.Column(db.Integer, nullable=False, primary_key=True)
    name = db.Column(db.String(100), nullable=False)
    main_company = db.Column(db.Integer, nullable=False, default='1')
    subsidiary_of = db.Column(db.Integer, nullable=True, default='')
    website = db.Column(db.String(100), nullable=True, default='')
    street = db.Column(db.String(100), nullable=False)
    street_no = db.Column(db.Integer, nullable=False)
    city = db.Column(db.String(100), nullable=False)
    post_code = db.Column(db.Integer, nullable=False)
    state = db.Column(db.String(100), nullable=False)
    classification = db.Column(db.Integer, nullable=False, default=0)
    comment = db.Column(db.String(300), nullable=True)
    image_file = db.Column(db.String(20), nullable=False, default='default_company.jpg')
    upload_date = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
    last_update_date = db.Column(db.DateTime, nullable=False, default=datetime.utcnow, onupdate=datetime.utcnow)

    # One To Many relationships where indexes can point o mutiple companies.
    # Example : One Legal_entity could cocern multiple companies. (There are surely more than just one GmBH)
    country_id = db.Column(db.Integer, db.ForeignKey('country.id'), nullable=False)
    legal_entity_id = db.Column(db.Integer, db.ForeignKey('company_legal_entity.id'), nullable=False)
    relation_id = db.Column(db.Integer, db.ForeignKey('company_relation.id'), nullable=False)
    industry_id = db.Column(db.Integer, db.ForeignKey('industry.id'), nullable=False)
    status_id = db.Column(db.Integer, db.ForeignKey('company_status.id'), nullable=False)

    # One To Many relationships for a company having mutliple elements of the following indexes
    # Example : One company would/could have many eployees
    employees = db.relationship('Person', backref='employer', lazy=True)
    projects = db.relationship('Project', backref='belongs_to', lazy=True)
    elements = db.relationship('Project_element', backref='company_ship_to', viewonly=True, lazy=True)
    notes = db.relationship('Company_note', backref='company', lazy=True)
    products = db.relationship('Product', backref='manufacturer', lazy=True)


    # returns a more information-rich, or official, string representation of an object
    # >>> company.query.all()
    # [1, ComanyName, CompanyCounntry] (Do not change this presentation
    # it will corrupt: the getCompanyId function in minibase.dabase.utils
    def __repr__(self):
        return f"{self.name}, {self.country_bill}, {self.id}"


class Company_relation(db.Model):
    id = db.Column(db.Integer, nullable=False, primary_key=True)
    name = db.Column(db.String(50), nullable=False)
    description = db.Column(db.String(300), nullable=False)
    companies = db.relationship('Company', backref='relation', lazy=True)

    # returns a more information-rich, or official, string representation of an object
    def __repr__(self):
        return f"{self.name}"


class Company_legal_entity(db.Model):
    id = db.Column(db.Integer, nullable=False, primary_key=True)
    name = db.Column(db.String(50), nullable=False)
    description = db.Column(db.String(300), nullable=False)
    companies = db.relationship('Company', backref='legal_entiy', lazy=True)

    # returns a more information-rich, or official, string representation of an object
    def __repr__(self):
        return f"{self.name}"


class Company_note(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    priority = db.Column(db.Integer, nullable=False, default='0')
    title = db.Column(db.String(100), nullable=False)
    content = db.Column(db.Text, nullable=False)
    date_posted = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
    date_due = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)

    company_id = db.Column(db.Integer, db.ForeignKey('company.id'), nullable=False)
    status_id = db.Column(db.Integer, db.ForeignKey('note_status.id'), nullable=False)

    # returns a more information-rich, or official, string representation of an object
    def __repr__(self):
        return f"{self.title}, {self.content}"


###################################################################################################
# Project
###################################################################################################
class Project(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), nullable=False)
    description = db.Column(db.String(300), nullable=False)
    date_prototype = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
    qte_prototype = db.Column(db.Integer, nullable=False)
    date_start = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
    qte_start = db.Column(db.Integer, nullable=False)
    date_production = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
    qte_production = db.Column(db.Integer, nullable=False)
    upload_date = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
    last_update_date = db.Column(db.DateTime, nullable=False, default=datetime.utcnow, onupdate=datetime.utcnow)
    image_file = db.Column(db.String(30), nullable=False, default='default_project.jpg')

    # One To Many relationships where indexes can point o mutiple compani30.
    company_id = db.Column(db.Integer, db.ForeignKey('company.id'), nullable=False)
    status_id = db.Column(db.Integer, db.ForeignKey('project_status.id'), nullable=False)
    industry_id = db.Column(db.Integer, db.ForeignKey('industry.id'), nullable=False)
    owner_id = db.Column(db.Integer, db.ForeignKey('person.id'), nullable=True)

    # One To Many relationships for a company having mutliple elements of the following indexes
    # Example : One company would/could have many eployees
    elements = db.relationship('Project_element', backref='project', lazy=True)
    notes = db.relationship('Project_note', backref='project', lazy=True)

    # returns a more information-rich, or official, string representation of an object
    def __repr__(self):
        return f"{self.name}"

class Project_element(db.Model):
    id = db.Column(db.Integer, nullable=False, primary_key=True)
    name = db.Column(db.String(100), nullable=False)
    description = db.Column(db.String(300), nullable=False)
    qte_per_project = db.Column(db.Integer, nullable=False, default='1')
    upload_date = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
    last_update_date = db.Column(db.DateTime, nullable=False, default=datetime.utcnow, onupdate=datetime.utcnow)

    company_ship_to_id = db.Column(db.Integer, db.ForeignKey('company.id'), nullable=False)
    project_id = db.Column(db.Integer, db.ForeignKey('project.id'), nullable=False)
    owner_id = db.Column(db.Integer, db.ForeignKey('person.id'), nullable=False)
    status_id = db.Column(db.Integer, db.ForeignKey('project_status.id'), nullable=False)

    # returns a more information-rich, or official, string representation of an object
    def __repr__(self):
        return f"{self.name}"

class Project_status(db.Model):
    id = db.Column(db.Integer, nullable=False, primary_key=True)
    name = db.Column(db.String(50), nullable=False)
    description = db.Column(db.String(300), nullable=False)
    upload_date = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
    last_update_date = db.Column(db.DateTime, nullable=False, default=datetime.utcnow, onupdate=datetime.utcnow)

    projects = db.relationship('Project', backref='status', lazy=True, viewonly=True)
    elements = db.relationship('Project_element', backref='element_status', lazy=True, viewonly=True)

    # returns a more information-rich, or official, string representation of an object
    def __repr__(self):
        return f"{self.name}"


class Project_note(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    priority = db.Column(db.Integer, nullable=False, default='0')
    title = db.Column(db.String(100), nullable=False)
    content = db.Column(db.Text, nullable=False)
    date_posted = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
    date_due = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)

    project_id = db.Column(db.Integer, db.ForeignKey('project.id'), nullable=False)
    status_id = db.Column(db.Integer, db.ForeignKey('note_status.id'), nullable=False)

    # returns a more information-rich, or official, string representation of an object
    def __repr__(self):
        return f"{self.title}, {self.content}"

###################################################################################################
# Product
###################################################################################################

class Product(db.Model):
    id = db.Column(db.Integer, nullable=False, primary_key=True)
    name  = db.Column(db.String(100), nullable=False)
    ordering_code  = db.Column(db.String(100), nullable=False)
    buy_cost  = db.Column(db.Float, nullable=False)
    comment  = db.Column(db.String(300), nullable=True)
    comment_manufacturer   = db.Column(db.String(300), nullable=True)
    currency = db.Column(db.String(50), nullable=False)
    description  = db.Column(db.String(300), nullable=False)
    last_time_buy_date  = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
    lead_time_days = db.Column(db.Integer, nullable=False)
    minimum_awarding_quantity  = db.Column(db.Integer, nullable=False)
    minimum_order_quantity  = db.Column(db.Integer, nullable=False)
    minimum_quote_quantity  = db.Column(db.Integer, nullable=False)
    obsolete_date   = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
    pollution_level = db.Column(db.String(50), nullable=True)
    price_change_flag = db.Column(db.Boolean, nullable=False, default=False)
    proposed_margin   = db.Column(db.Float, nullable=True)
    upload_date = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
    last_update_date = db.Column(db.DateTime, nullable=False, default=datetime.utcnow, onupdate=datetime.utcnow)

    production_country_id = db.Column(db.Integer, db.ForeignKey('country.id'), nullable=True)
    classification_id = db.Column(db.Integer, db.ForeignKey('product_classification.id'), nullable=True)
    domain_id = db.Column(db.Integer, db.ForeignKey('product_domain.id'), nullable=True)
    category_id = db.Column(db.Integer, db.ForeignKey('product_category.id'), nullable=True)
    sub_category_id = db.Column(db.Integer, db.ForeignKey('product_sub_category.id'), nullable=True)

    status_id = db.Column(db.Integer, db.ForeignKey('product_status.id'), nullable=False)
    eligibility_id = db.Column(db.Integer, db.ForeignKey('product_eligibility.id'), nullable=False)

    packaging_id = db.Column(db.Integer, db.ForeignKey('product_packaging.id'), nullable=True)
    physical_id = db.Column(db.Integer, db.ForeignKey('product_physical.id'), nullable=True)
    manufacturer_id = db.Column(db.Integer, db.ForeignKey('company.id'), nullable=False)


class Product_status(db.Model):
    id = db.Column(db.Integer, nullable=False, primary_key=True)
    name = db.Column(db.String(50), nullable=False)
    description = db.Column(db.String(300), nullable=False)

    products = db.relationship('Product', backref='status', lazy=True)

    # returns a more information-rich, or official, string representation of an object
    def __repr__(self):
        return f"{self.name}"


class Product_eligibility(db.Model):
    id = db.Column(db.Integer, nullable=False, primary_key=True)
    name = db.Column(db.String(50), nullable=False)
    description = db.Column(db.String(300), nullable=False)

    products = db.relationship('Product', backref='eligibility', lazy=True)

    # returns a more information-rich, or official, string representation of an object
    def __repr__(self):
        return f"{self.name}"


class Product_classification(db.Model):
    id = db.Column(db.Integer, nullable=False, primary_key=True)
    name = db.Column(db.String(50), nullable=False)
    description = db.Column(db.String(300), nullable=False)

    products = db.relationship('Product', backref='classification', lazy=True)

    # returns a more information-rich, or official, string representation of an object
    def __repr__(self):
        return f"{self.name}"


class Product_domain(db.Model):
    id = db.Column(db.Integer, nullable=False, primary_key=True)
    name = db.Column(db.String(50), nullable=False)
    description = db.Column(db.String(300), nullable=False)

    products = db.relationship('Product', backref='domain', lazy=True)

    # returns a more information-rich, or official, string representation of an object
    def __repr__(self):
        return f"{self.name}"


class Product_category(db.Model):
    id = db.Column(db.Integer, nullable=False, primary_key=True)
    name = db.Column(db.String(50), nullable=False)
    description = db.Column(db.String(300), nullable=False)

    products = db.relationship('Product', backref='category', lazy=True)

    # returns a more information-rich, or official, string representation of an object
    def __repr__(self):
        return f"{self.name}"


class Product_sub_category(db.Model):
    id = db.Column(db.Integer, nullable=False, primary_key=True)
    name = db.Column(db.String(50), nullable=False)
    description = db.Column(db.String(300), nullable=False)

    products = db.relationship('Product', backref='sub_category', lazy=True)

    # returns a more information-rich, or official, string representation of an object
    def __repr__(self):
        return f"{self.name}"


class Product_packaging(db.Model):
    id = db.Column(db.Integer, nullable=False, primary_key=True)
    name = db.Column(db.String(50), nullable=False)
    description = db.Column(db.String(300), nullable=False)
    unit = db.Column(db.Integer)
    quantity = db.Column(db.Integer)

    products = db.relationship('Product', backref='packaging', lazy=True)

    # returns a more information-rich, or official, string representation of an object
    def __repr__(self):
        return f"{self.name}"


class Product_physical(db.Model):
    id = db.Column(db.Integer, nullable=False, primary_key=True)
    name = db.Column(db.String(50), nullable=False)
    description = db.Column(db.String(300), nullable=False)
    image_file = db.Column(db.String(20), nullable=False, default='default_product.jpg')
    pitch_x = db.Column(db.Float, nullable=True)
    pitch_y = db.Column(db.Float, nullable=True)
    size_x = db.Column(db.Float, nullable=True)
    size_y = db.Column(db.Float, nullable=True)
    size_z = db.Column(db.Float, nullable=True)

    products = db.relationship('Product', backref='physical', lazy=True)
    # returns a more information-rich, or official, string representation of an object
    def __repr__(self):
        return f"{self.name}"
