import psycopg2
import re
import config as cfg
import data as d


def init_tables():
    DB_NAME, DB_USER = cfg.database_name, cfg.database_user
    try:
        connection = psycopg2.connect("dbname=%s user=%s" %(DB_NAME, DB_USER))
    except Exception as e:
        print(e)
    cursor = connection.cursor()
    #checks for anime_list table
    cursor.execute("CREATE TABLE IF NOT EXISTS HorribleSubs(title text, quality text, UNIQUE(title, quality));")

    cursor.execute("CREATE TABLE IF NOT EXISTS DeadFish(title text, quality text, UNIQUE(title, quality));")
    #cursor.execute("CREATE TABLE IF NOT EXISTS subgroups(subgroup text UNIQUE, nyaa_id text);")
    cursor.execute("CREATE TABLE IF NOT EXISTS downloaded(title text, episode integer, date timestamp, subgroup text, status text, UNIQUE(title, episode, subgroup));")
    connection.commit()
    connection.close()

def selector(m, valid_selection):
    while True:
        try:
            input_search = int(input(m)) - 1
            assert(input_search < valid_selection and input_search >= 0)
            return(input_search)
            break
        except:
            print('Input not recognized. Enter a valid NUMBER corresponding to the choice.')
            pass

def selection(selection):
    for i in range(len(selection)):
        print('%d - %s' %(i + 1, selection[i]))

#Used in subgroups.py to get a feed.
def get_rss_feed(input_title, user_id, i):
    if not input_title:
        return('http://nyaa.se/?page=rss&user=%s&offset=%d' %(user_id, i))
    else:
        return('http://nyaa.se/?page=rss&term=%s&user=%s&offset=%d' %(input_title, user_id, i))

def get_title(title, title_regex=None):
    parsed_title = ''
    if not title_regex:
            for subgroup in d.available_subgroups:
                try:
                    parsed_title = re.search(subgroup['regex']['title'], title).group(0)
                except Exception as e:
                    print(e)
                    pass
                if parsed_title:
                    break
    else:
        try:
            parsed_title = re.search(title_regex, title).group(0)
        except Exception as e:
            print(e)

    return(parsed_title)

def get_episode(title, episode_regex):

    try:
        parsed_episode = re.search(episode_regex, title).group(0)
    except Exception as e:
        print(e)

    return(parsed_episode)
       

   





    

    
