#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
Stashr - Database Definition
"""

"""
MIT License

Copyright (c) 2020 Andrew Vanderbye

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""

"""-------------------------------------------------------------------------------------------
-- IMPORTS
-------------------------------------------------------------------------------------------"""

""" --- HUEY IMPORT --- """
""" --- PYTHON IMPORTS --- """
import os
from datetime import datetime

""" --- STASHR DEPENDENCY IMPORTS --- """
""" --- STASHR CORE IMPORTS --- """
from stashr import log, paths, folders
# from folders import StashrPaths

""" --- FLASK EXTENSION IMPORTS --- """
from flask_login import UserMixin
from flask_bcrypt import generate_password_hash

""" --- SQLALCHEMY IMPORTS --- """
from sqlalchemy import *
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import *

""" --- CREATE LOGGER --- """
logger = log.stashr_logger(__name__)

""" --- CREATE SQLITE ENGINE --- """
engine = create_engine('sqlite:///{0}'.format(paths.db_path),
                       connect_args={'check_same_thread': False, 'timeout': 15},
                       echo=False)

Base = declarative_base()

from marshmallow_sqlalchemy import ModelSchema, SQLAlchemyAutoSchema, SQLAlchemySchema, auto_field
from marshmallow import fields
from marshmallow_sqlalchemy.fields import Nested

"""-------------------------------------------------------------------------------------------
-- DATABASE
-------------------------------------------------------------------------------------------"""

""" --- RATINGS --- """

RATING_A = 0
RATING_T = 1
RATING_T_PLUS = 2
RATING_PA = 3
RATING_EX = 4
RATING_UR = 5

ratings_dict = [
    "E",
    "T",
    "T+",
    "PA",
    "Ex",
    "UR",
]

ratings_dict_words = {
    0: 'Everyone',
    1: 'Teen',
    2: 'Teen+',
    3: 'Parental Advisory',
    4: 'Explicit',
    5: 'Unrated',
}

reverse_ratings_dict = {
    'Everyone': 0,
    'Teen': 1,
    'Teen+': 2,
    'Parental Advisory': 3,
    'Explicit': 4,
    'Unrated': 5,
}


""" --- DATABASE TABLES --- """


class Users(Base, UserMixin):
    __tablename__ = 'users'

    id = Column(Integer, primary_key=True)

    # AUTHENTICATION INFORMATION
    username = Column(String(50), nullable=False, unique=true, server_default='')
    password = Column(String(50), nullable=False, server_default='')

    # USER PERMISSIONS
    role = Column(String(100), nullable=False, server_default='reader')
    rating_allowed = Column(Integer, ForeignKey('age_ratings.rating_value'), nullable=False, server_default='0')

    # USER EMAIL INFORMATION
    email = Column(String(255), nullable=False, unique=True, server_default='')
    confirmed_at = Column(DateTime()) # REMOVE?

    # USER INFORMATION
    is_active = Column(Boolean(), nullable=False, server_default='0') # REMOVE?

    # USER API KEY
    api_key = Column(String, server_default='')

    # USER LISTS
    user_reading_list = relationship('ReadingLists', backref='user', lazy='dynamic')

    # JOINS
    age_rating_title = relationship('AgeRatings', 
                                    primaryjoin='Users.rating_allowed == AgeRatings.rating_value',
                                    backref='users',
                                    lazy='joined')

class Volumes(Base):
    __tablename__ = 'volumes'

    volume_id = Column(Integer, ForeignKey('directory_link.directory_volume_id'), primary_key=True)

    # VOLUME INFORMATION
    volume_name = Column(String)
    volume_description = Column(String)
    volume_year = Column(String(4))
    volume_publisher_id = Column(Integer, ForeignKey('publishers.publisher_id'))
    volume_url = Column(String)

    # VOLUME IMAGE URL
    volume_image = Column(String)

    # VOLUME DETAILS
    volume_latest = Column(String)
    volume_have = Column(String)
    volume_total = Column(String)
    volume_status = Column(Boolean, server_default='0')
    volume_last_update = Column(Date)

    # VOLUME STASHR INFO
    volume_path = Column(String)
    volume_age_rating = Column(Integer, server_default=str(RATING_UR))
    volume_slug = Column(String, unique=True)
    volume_sort_title = Column(String)

    # JOINS
    publisher = relationship('Publishers',
                             primaryjoin='Volumes.volume_publisher_id == Publishers.publisher_id',
                             backref='volumes',
                             lazy='joined')
    
    age_rating = relationship('AgeRatings',
                              primaryjoin='Volumes.volume_age_rating == AgeRatings.rating_value',
                              backref='volumes',
                              lazy='joined')

    directory = relationship('Directories',
                             primaryjoin='Volumes.volume_id == Directories.directory_volume_id', 
                             backref='volumes',
                             lazy='joined')


class Issues(Base):
    __tablename__ = 'issues'

    issue_id = Column(Integer, primary_key=True)

    # FOREIGN KEY RELATION
    issue_volume_id = Column(Integer, ForeignKey('volumes.volume_id'))

    # ISSUE INFORMATION
    issue_name = Column(String)
    issue_number = Column(String)
    issue_release_date = Column(String)
    issue_description = Column(String)

    # ISSUE IMAGE URL
    issue_cover_url = Column(String)

    # ISSUE STASHR DETAILS
    issue_file_status = Column(Boolean, server_default='0')
    issue_file_date = Column(Date)
    issue_file_path = Column(String)

    # ADDITIONAL ISSUE INFO
    issue_character_credits = Column(String)
    issue_person_credits = Column(String)
    issue_story_arc_credits = Column(String)
    issue_team_credits = Column(String)

    issue_json = Column(String)

    # JOINS
    volume = relationship('Volumes',
                          primaryjoin='Issues.issue_volume_id == Volumes.volume_id',
                          backref='issues',
                          lazy='joined')
    
    read_status = relationship('ReadIssues',
                               primaryjoin='Issues.issue_id == ReadIssues.read_issue_id',
                               backref='issues')

    owned_status = relationship('OwnedIssues',
                                primaryjoin='Issues.issue_id == OwnedIssues.owned_issue_id',
                                backref='issues')
    
    
    collections = relationship('CollectionLinks',
                                primaryjoin='Issues.issue_id == CollectionLinks.collection_link_issue_id',
                                backref='issues')

    readinglist = relationship('ReadingLists',
                                primaryjoin='Issues.issue_id == ReadingLists.reading_list_issue_id',
                                backref='issues')


class NewReleases(Base):
    __tablename__ = 'new_releases'

    new_release_id = Column(Integer, primary_key=True)

    new_release_issue_id = Column(Integer, ForeignKey('issues.issue_id'))
    new_release_volume_id = Column(Integer, ForeignKey('volumes.volume_id'))

    new_release_comic_name = Column(String)
    new_release_issue_number = Column(String)
    new_release_publisher_id = Column(Integer)
    new_release_publish_date = Column(String)

    new_release_item_url = Column(String)
    new_release_image_url = Column(String)

    # JOINS
    status = relationship('Volumes',
                          primaryjoin='NewReleases.new_release_volume_id == Volumes.volume_id',
                          backref='new_releases',
                          lazy='select')

    publisher = relationship('Publishers',
                             primaryjoin='NewReleases.new_release_publisher_id == Publishers.publisher_id',
                             backref='new_releases',
                             viewonly=True,
                             sync_backref=False,
                             lazy='joined')


class ReadIssues(Base):
    __tablename__ = 'issues_read_link'

    read_id = Column(Integer, primary_key=True)

    read_user_id = Column(Integer, ForeignKey('users.id'))
    read_issue_id = Column(Integer, ForeignKey('issues.issue_id'))
    read_volume_id = Column(Integer, ForeignKey('volumes.volume_id'))

    read_status = Column(Boolean, unique=False)


class OwnedIssues(Base):
    __tablename__ = 'issues_owned_link'

    def as_dict(self):
        return {c.name: getattr(self, c.name) for c in self.__table__.columns}

    owned_id = Column(Integer, primary_key=True)

    owned_user_id = Column(Integer, ForeignKey('users.id'))
    owned_issue_id = Column(Integer, ForeignKey('issues.issue_id'))
    owned_volume_id = Column(Integer, ForeignKey('volumes.volume_id'))

    owned_status = Column(Boolean, unique=False)


class Collections(Base):
    __tablename__ = 'collections'

    collection_id = Column(Integer, primary_key=True)

    collection_user_id = Column(Integer, ForeignKey('users.id'))

    collection_name = Column(String)
    collection_slug = Column(String)
    collection_sort_title = Column(String)
    collection_public = Column(Boolean, server_default='0')

    collection_age_rating = Column(Integer, server_default=str(RATING_UR))

    collection_description = Column(String)
    collection_cover_image = Column(Integer)

    user = relationship('Users',
                        primaryjoin='Collections.collection_user_id == Users.id',
                        backref='collections',
                        lazy='joined')


class CollectionLinks(Base):
    __tablename__ = 'collection_issues'

    collection_link_id = Column(Integer, primary_key=True)

    collection_link_collection_id = Column(Integer, ForeignKey('collections.collection_id'))
    collection_link_issue_id = Column(Integer, ForeignKey('issues.issue_id'))
    collection_link_issue_position = Column(Integer)

    issue = relationship('Issues',
                         primaryjoin='CollectionLinks.collection_link_issue_id == Issues.issue_id',
                         backref='collection_issues',
                         lazy='joined')

    collection = relationship('Collections',
                              primaryjoin='CollectionLinks.collection_link_collection_id == Collections.collection_id',
                              backref='collection_issues',
                              lazy='joined')

class ReadingLists(Base):
    __tablename__ = 'reading_lists'

    reading_list_id = Column(Integer, primary_key=True)

    reading_list_user_id = Column(Integer, ForeignKey('users.id'))
    reading_list_volume_id = Column(Integer)
    reading_list_issue_id = Column(Integer, ForeignKey('issues.issue_id'))
    reading_list_position = Column(Integer, unique=False)

    issue = relationship('Issues',
                         primaryjoin='ReadingLists.reading_list_issue_id == Issues.issue_id',
                         backref='reading_lists',
                         lazy='joined')


class Characters(Base):
    __tablename__ = 'characters'

    character_id = Column(Integer, primary_key=True)

    character_name = Column(String)
    character_description = Column(String)
    character_image = Column(String)
    character_issue_credits = Column(String)
    character_volume_credits = Column(String)


class People(Base):
    __tablename__ = 'people'

    person_id = Column(Integer, primary_key=True)

    person_name = Column(String)
    person_image = Column(String)
    person_website = Column(String)
    person_description = Column(String)


class Publishers(Base):
    __tablename__ = 'publishers'

    publisher_id = Column(Integer, ForeignKey('new_releases.new_release_publisher_id'), primary_key=True)

    publisher_image = Column(String)
    publisher_name = Column(String)
    publisher_description = Column(String)


class StoryArcs(Base):
    __tablename__ = 'story_arcs'

    story_arc_id = Column(Integer, primary_key=True)

    story_arc_description = Column(String)
    story_arc_image = Column(String)
    story_arc_count_of_issues = Column(Integer)
    story_arc_issues = Column(String)


class AgeRatings(Base):
    __tablename__ = 'age_ratings'

    rating_id = Column(Integer, primary_key=True)

    rating_value = Column(Integer, ForeignKey('volumes.volume_age_rating'))
    rating_short = Column(String)
    rating_long = Column(String)


class Libraries(Base):
    __tablename__ = 'libraries'

    library_id = Column(Integer, primary_key=True)

    library_default = Column(Boolean, server_default='0')
    library_path = Column(String)

class Directories(Base):
    __tablename__ = 'directory_link'

    directory_id = Column(Integer, primary_key=True)

    directory_volume_id = Column(Integer, ForeignKey('volumes.volume_id'), unique=True)
    directory_path= Column(String)
    directory_in_library = Column(Boolean, server_default='0')
    

class ScrapeItems(Base):
    __tablename__ = 'scrape_items'

    scrape_id = Column(Integer, primary_key=True)

    scrape_directory_id = Column(Integer, ForeignKey('directory_link.directory_id'))
    scrape_directory = Column(String, unique=True)

    scrape_match = Column(Boolean, server_default='0')
    scrape_add = Column(Boolean, server_default='0')
    scrape_candidate = Column(Integer)
    scrape_json = Column(String)

    directory = relationship('Directories', 
                             primaryjoin='ScrapeItems.scrape_directory_id == Directories.directory_id',
                             backref='scrape_items',
                             lazy='joined')


"""-------------------------------------------------------------------------------------------
-- DATABASE SCHEMAS
-------------------------------------------------------------------------------------------"""

class PublishersSchema(SQLAlchemyAutoSchema):
    class Meta:
        include_fk = True
        model = Publishers


class AgeRatingsSchema(SQLAlchemyAutoSchema):
    class Meta:
        include_fk = True
        model = AgeRatings


class UsersSchema(SQLAlchemySchema):
    class Meta:
        include_fk = True
        model = Users

    id = auto_field()
    username = auto_field()
    role = auto_field()
    rating_allowed = auto_field()
    email = auto_field()
    
    age_rating_title = Nested(AgeRatingsSchema)


class DirectoriesSchema(SQLAlchemyAutoSchema):
    class Meta:
        model = Directories


class VolumesSchema(SQLAlchemyAutoSchema):
    class Meta:
        include_fk = True
        model = Volumes

    publisher = Nested(PublishersSchema)
    age_rating = Nested(AgeRatingsSchema, many=True)
    directory = Nested(DirectoriesSchema)


class NewReleasesSchema(SQLAlchemyAutoSchema):
    class Meta:
        include_fk = True
        model = NewReleases

    status = Nested(VolumesSchema)
    publisher = Nested(PublishersSchema)


class ReadIssuesSchema(SQLAlchemyAutoSchema):
    class Meta:
        model = ReadIssues
        include_fk = True


class OwnedIssuesSchema(SQLAlchemyAutoSchema):
    class Meta:
        model = OwnedIssues


class CollectionsSchema(SQLAlchemyAutoSchema):
    class Meta:
        model = Collections

    user = Nested(UsersSchema)


class IssuesSchema(SQLAlchemyAutoSchema):
    class Meta:
        model = Issues
       
    volume = Nested(VolumesSchema)
    read_status = Nested(ReadIssuesSchema, many=True)
    owned_status = Nested(OwnedIssuesSchema, many=True)


class CollectionLinksSchema(SQLAlchemyAutoSchema):
    class Meta:
        model = CollectionLinks

    issue = Nested(IssuesSchema)
    collection = Nested(CollectionsSchema)


class ReadingListsSchema(SQLAlchemyAutoSchema):
    class Meta:
        model = ReadingLists

    issue = Nested(IssuesSchema)


class CharactersSchema(SQLAlchemyAutoSchema):
    class Meta:
        model = Characters


class PeopleSchema(SQLAlchemyAutoSchema):
    class Meta:
        model = People


class StoryArcsSchema(SQLAlchemyAutoSchema):
    class Meta:
        model = StoryArcs


class ScrapeItemsSchema(SQLAlchemyAutoSchema):
    class Meta:
        model = ScrapeItems

    directory = Nested(DirectoriesSchema)

"""-------------------------------------------------------------------------------------------
-- DATABASE DEFINITION
-------------------------------------------------------------------------------------------"""

Session = sessionmaker(bind=engine)
session = Session()

"""-------------------------------------------------------------------------------------------
-- DATABASE FUNCTIONS
-------------------------------------------------------------------------------------------"""


# Create Default Admin Account
def create_default_admin():

    user = Users()

    user.username = 'admin'
    user.password = generate_password_hash('admin123').decode('utf-8')
    user.role = 'admin'
    user.email = 'no@email.com'
    user.confirmed_at = datetime.now()
    user.is_active = True
    user.rating_allowed = RATING_UR

    session.add(user)
    session.commit()


def create_default_age_ratings():

    json = []

    rating_e = {
        "rating_value": 0,
        "rating_short": 'E',
        "rating_long": 'Everyone'
    }
    rating_t = {
        "rating_value": 1,
        "rating_short": 'T',
        "rating_long": 'Teen'
    }
    rating_t_plus = {
        "rating_value":2,
        "rating_short": 'T+',
        "rating_long": 'Teen+'
    }
    rating_pa = {
        "rating_value": 3,
        "rating_short": 'PA',
        "rating_long": 'Parental Advisory'
    }
    rating_ex = {
        "rating_value": 4,
        "rating_short": 'Ex',
        "rating_long": 'Explicit'
    }
    rating_ur = {
        "rating_value": 5,
        "rating_short": 'UR',
        "rating_long": 'Unrated'
    }

    json.append(rating_e)
    json.append(rating_t)
    json.append(rating_t_plus)
    json.append(rating_pa)
    json.append(rating_ex)
    json.append(rating_ur)

    print(json)

    for rating in json:
        new_rating = AgeRatings()
        new_rating.rating_value = rating['rating_value']
        new_rating.rating_short = rating['rating_short']
        new_rating.rating_long = rating['rating_long']

        session.add(new_rating)

    session.commit()


# Migrate Database
def migrate_database():
    # CHECK FOR NEW DATABASE TABLES
    if not engine.dialect.has_table(engine.connect(), "directory_link"):
        Directories.__table__.create(bind=engine)
    # CHECK FOR NEW TABLE COLUMNS


# Create Database
if not os.path.exists(folders.StashrPaths().db_path()):
    print(f'PATH: {folders.StashrPaths().db_path()}')
    try:
        logger.debug('Creating Database')
        Base.metadata.create_all(engine)
        create_default_admin()
        create_default_age_ratings()
    except Exception as e:
        logger.error('Problem Creating Database')
        logger.error(e)
        raise e
else:
    logger.debug('Database Exists')
    try:
        Base.metadata.create_all(engine)
        migrate_database()
    except Exception as e:
        logger.error('Problem Accessing Database')
        logger.error(e)
