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

"""
Stashr - Filename Parsing Functions
"""

"""
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 datetime, time, pathlib, os, re

""" --- STASHR DEPENDENCY IMPORTS --- """

""" --- STASHR CORE IMPORTS --- """
from stashr import log, database
from stashr.comicvine import cv
from stashr.config import stashrconfig

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

"""-------------------------------------------------------------------------------------------
-- FILENAME PARSER FUNCTIONS
-------------------------------------------------------------------------------------------"""

def repl(filename):
    return ' ' * len(filename.group())


def fixSpaces( string, remove_dashes=True ):
    if remove_dashes:
        placeholders = ['[-_]','  +']
    else:
        placeholders = ['[_]','  +']
    for ph in placeholders:
        string = re.sub(ph, repl, string )
    return string #.strip()


def getIssueNumber(filename):

    found = False
    issue = ''

    filename = pathlib.Path(filename).stem

    filename = filename.replace("+", " ")
    filename = filename.replace("-", " ")

    filename = re.sub( "\(.*?\)", repl, filename)
    filename = re.sub( "\[.*?\]", repl, filename)

    filename = fixSpaces(filename)

    filename = re.sub( "of [\d]+", repl, filename)

    word_list = []

    for m in re.finditer("\S+", filename):
        word_list.append(m.group(0))

    if len(word_list) == 1:
        return issue

    for w in reversed(word_list):
        if re.match("\#\d*", w[0]):
            found = True
            break

    if not found:
        w = word_list[-1]
        if re.match('\d*', w[0]):
            found = True
    
    if not found:
        for w in reversed(word_list):
            if re.match("\#\S+", w[0]):
                found = True
                break
    if found:
        issue = w
        if issue[0] == '#':
            issue = issue[1:]
        issue = issue.lstrip('0') or 0

    return issue