#!/usr/bin/env python
# =======================================================================
# title             :SerialDo0n
# description       :This program displays Information About Tv Series
# author            :LinArcX
# date              :03/21/2017
# version           :0.1
# mail              :linarcx@gmail.com
# web               :stack.blog.ir
# notes             :
# python_version    :3.6.0
# main api:         :http://www.tvmaze.com/api
# second api:       :https://www.episodate.com/api
# =======================================================================

# Import the modules needed to run the script.
import sys
import os
import pwd
import json
import re
import requests
from collections import namedtuple
from os.path import expanduser
from prettytable import PrettyTable
from pyfiglet import figlet_format
import tvdb_api

# Url definition
searchUrl = "http://api.tvmaze.com/search/shows?q="
peopleUrl = 'http://api.tvmaze.com/search/people?q='
upComingUrl = 'http://api.tvmaze.com/schedule?date='
showUrl = 'http://api.tvmaze.com/shows'
showUrlByPage = ' http://api.tvmaze.com/shows?page='

# init tvdb_api
t = tvdb_api.Tvdb(banners=True)

# Global Section Variables
PATH = expanduser("~") + "/.config/tvdoon/"

# =======================
#     MENUS FUNCTIONS
# =======================


class color:
    PURPLE = '\033[95m'
    CYAN = '\033[96m'
    DARKCYAN = '\033[36m'
    BLUE = '\033[94m'
    GREEN = '\033[92m'
    YELLOW = '\033[93m'
    RED = '\033[91m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'
    ITALIC = '\e[3m'
    END = '\033[0m'


def main_menu():
    os.system('clear')
    checkConfExist()
    username = pwd.getpwuid(os.getuid()).pw_name
    print(color.BOLD + figlet_format('TvDo0n', font='starwars') + color.END)
    print("Welcome " + username + ", Please Choose The Items:")
    print("s. Search Tv Series")
    print("m. My Favourites")
    print("w. Who Am I?")
    # print("x. truct")
    print("h. Help")
    print("c. Clear Screen")
    print("\nq. Quit")
    switchCreator("smwhcq","","")
    return


def checkConfExist():
    # create conf directory
    if not os.path.exists(PATH):
        os.makedirs(PATH)

    # create favourite.conf file
    try:
        favFile = open(PATH + "favourites.conf", "r")
    except (OSError, IOError) as e:
        open(PATH + "favourites.conf", "a").close()

    return


def searchTvSeries(pItems=None):
    items = ""
    flag = 0
    if pItems is None:
        os.system('clear')
        tVar = input("Enter Tv Show Name:")
        items = t.search(tVar)
        count = len(items)
    else:
        items = pItems
    x = PrettyTable()
    for i, item in enumerate(items):
        x.field_names = [i, "seriesname"]
        x.add_row([i, item['seriesname']])
    print(x)
    print(color.CYAN + "for see more details, enter 'row Number' and hit ENTER.otherwise use below Capabilities." + color.END)
    print("b. Back")
    print("q. Quit")
    while flag == 0:
        mainChoice = input(" >>  ")
        if mainChoice == 'b':
            main_menu()
        elif mainChoice == 'q':
            quit()
        elif re.match('\d',mainChoice):
            try:
                items = t.search(x._rows[int(mainChoice)][1])
                selectTvShow(items)
            except IndexError:
                print("You Entered Wrong Number.Please Try Again Later.")
        else:
            print("Invalid selection, please try again.\n")
    return


def selectTvShow(pItems):
    originalParams = "soabqfd"
    finalParams = ""
    choice = ""
    favExists = False
    items = pItems
    try:
        if pItems is None:
            choice = input(" >>  ")
            dict = pItems[int(choice)]
        else:
            dict = pItems[0]
            x = PrettyTable()
            # x.add_column(item['seriesname'], [1295, 5905, 112, 1357, 2058, 1566, 5386])
            x.add_column("No.", [choice])
            x.add_column("seriesname", [(t[dict['seriesname']]['seriesname'])])
            x.add_column("rating", [(t[dict['seriesname']]['rating'])])
            x.add_column("ratingcount", [(t[dict['seriesname']]['ratingcount'])])
            x.add_column("genre", [(t[dict['seriesname']]['genre'])])
            x.add_column("airs_dayofweek", [(t[dict['seriesname']]['airs_dayofweek'])])
            x.add_column("firstaired",[(t[dict['seriesname']]['firstaired'])])
            try:
                x.add_column("finale_aired", [(t[dict['seriesname']]['finale_aired'])])
            except Exception as e:
                x.add_column("finale_aired", ["---"])
            x.add_column("network", [(t[dict['seriesname']]['network'])])
            x.add_column("runtime", [(t[dict['seriesname']]['runtime'])])
            x.add_column("status", [(t[dict['seriesname']]['status'])])
            print(x)
    except ValueError:
        main_menu()
    except IndexError:
        print("Oops! You Enter Incorrect Number.Please Select Another Series Again: ")
        selectTvShow(items)

    favFile = open(PATH + "favourites.conf", "r")
    for line in favFile:
        if line == pItems[0]['seriesname'] + "\n":
            favExists = True
    favFile.close()
    if favExists:
        print(color.BOLD + color.CYAN + "This Is your Favourite Serie." + color.END)
        print("d. Delete From Favourites")
        finalParams = originalParams.replace("f", "")
    else:
        print("f. Favourite This!")
        finalParams = originalParams.replace("d", "")
    favFile.close()
    print("s. Search Another Tv Show")
    print("o. OverView")
    print("a. Actors")
    print("b. Back")
    print("q. Quit")
    switchCreator(finalParams, items, "searchTvSeries")
    return

def OverView(pItems):
    items = pItems
    dict = pItems[0]
    print("overview: \n")
    print(color.RED + str([(t[dict['seriesname']]['overview'])]) + color.END)
    print("b. Back")
    print("q. Quit")
    switchCreator("bqas", items, "selectTvShow")
    return

def actors(pItems):
    dict = pItems[0]
    x = PrettyTable()
    splitActors = str([(t[dict['seriesname']]['actors'])]).split("|")
    for i, item in enumerate(splitActors):
        x.field_names = [i, "actors"]
        x.add_row([i, color.GREEN + item + color.END])
    print(x)
    print("b. Back")
    print("q. Quit")
    switchCreator("qbos", pItems, "selectTvShow")
    return

def myFavourites():
    flag = 0
    x = PrettyTable()
    favFile = open(PATH + "favourites.conf", "r")
    if os.path.getsize(PATH + "favourites.conf") > 0:
        for i, line in enumerate(favFile):
            x.field_names = [i, "seriesname"]
            x.add_row([i, line])
        print(x)
        print("b. Back")
        print("q. Quit")
        favFile.close()
        while flag == 0:
            mainChoice = input(" >>  ")
            if mainChoice == 'b':
                main_menu()
            elif mainChoice == 'q':
                quit()
            elif re.match("\d", mainChoice):
                try:
                    items = t.search(x._rows[int(mainChoice)][1])
                    selectTvShow(items)
                except IndexError as e:
                    print("You Entered Wrong Number.Please Try Again Later.")
            else:
                print("Invalid selection, please try again.\n")
    else:
        favFile.close()
        print(color.RED + "there is no favourite tv show in the list!" + color.END)
        print("b. Back")
        print("q. Quit")
        switchCreator("qb", "", "main_menu")
    return


def deleteFavourites(pItems):
    dict = pItems[0]

    f = open(PATH + "favourites.conf", "r")
    rLines = f.readlines()
    f.close()

    f = open(PATH + "favourites.conf", "w")

    for line in rLines:
        if line != dict['seriesname'] + "\n":
            f.write(line)

    f.close()
    print(color.CYAN + "'" + dict['seriesname'] + "'" + " was Successfully removed from your favourite list" + color.END)
    print("b. Back")
    print("q. Quit")
    switchCreator("qbos", pItems, "selectTvShow")
    return


def favouriteThis(pItems):
    dict = pItems[0]
    favFile = open(PATH + "favourites.conf", "a")
    favFile.write( dict['seriesname']+ "\n")
    favFile.close()
    print(color.GREEN + "'" + dict['seriesname'] + "'" + " Successfully Added to Your Favourite List." +color.END )
    print("b. Back")
    print("q. Quit")
    switchCreator("qbos", pItems, "selectTvShow")
    # data = {}
    # data['key'] = 'value'
    # json_data = json.dumps(data)
    return


def whoAmI():
    print("i am nobody, please visit us on : http://www.bbs.archusers.ir!\n")
    print("b. Back")
    print("q. Quit")
    switchCreator("qb", "", "main_menu")
    return

def help():
    print("this program use english letters for get into other menu(sub-menu).\nfor example, if you see: 'b. Back', you must enter b letter, "+
          "and hit enter from keyboard.")
    print("b. Back")
    print("q. Quit")
    switchCreator("qb", "", "main_menu")
    return

def clear():
    os.system('clear')
    print("b. Back")
    print("q. Quit")
    switchCreator("qb", "", "main_menu")
    return

def quit():
    sys.exit()


def switchCreator(*args):

    """call the appropriate function, according to arguments pass it.

    :param args: args[0] =menu actions, args[1] =function parameters, args[2] =function name
    :return:
    """
    flag = 0
    while flag == 0:
        mainChoice = input(" >>  ")
        if mainChoice == 's' and 's' in args[0]:
            searchTvSeries()
        if mainChoice == 'm' and 'm' in args[0]:
            myFavourites()
        if mainChoice == 'f' and 'f' in args[0]:
            favouriteThis(args[1])
        if mainChoice == 'd' and 'd' in args[0]:
            deleteFavourites(args[1])
        elif mainChoice == 'w' and 'w' in args[0]:
            whoAmI()
        elif mainChoice == 'h' and 'h' in args[0]:
            help()
        elif mainChoice == 'c' and 'c' in args[0]:
            clear()
        elif mainChoice == 'q' and 'q' in args[0]:
            quit()
        elif mainChoice == 'o' and 'o' in args[0]:
            OverView(args[1])
        elif mainChoice == 'a' and 'a' in args[0]:
            actors(args[1])
        elif mainChoice == 'b' and 'b' in args[0]:
            if args[2] == "main_menu":
                result = main_menu()
                return result
            elif args[2] == "searchTvSeries":
                searchTvSeries(args[1])
            elif args[2] == "selectTvShow":
                selectTvShow(args[1])
        else:
            print("Invalid selection, please try again.\n")


def functionCaller(methodToRun):
    result = methodToRun()
    return result

def getTvObj():
    choice = input(" >>  ")
    resp = requests.get(searchUrl + choice)
    return json.loads(resp.content.decode('utf-8'), object_hook=lambda d: namedtuple('X', d.keys())(*d.values()))

def truct():
    #client-id = 87f242aaa6dd444422926ef424ebd1f86567fee2810914ca98154601b0cfc899
    #client-secret-id=dbdb42b6a0a7039f652dd24330fc7a8a3e6083062978fb8e755520ed21ad4f70
    # payload = {'Content-type': 'application/json',
    #            'trakt-api-key': '87f242aaa6dd444422926ef424ebd1f86567fee2810914ca98154601b0cfc899',
    #            'trakt-api-version': '2'}
    # resp = requests.get('https://api.trakt.tv', params=payload)
    # print(resp.headers)

    # p = lambda: None
    # p = getTvObj()
    choice = input(" >>  ")
    resp = requests.get(searchUrl + choice)
    p=json.loads(resp.content)
    print(p[0].score)


# =======================
#    MENUS DEFINITIONS
# =======================
# Menu definition

menu_actions = {
    'main_menu': main_menu,
    's': searchTvSeries,
    'w': whoAmI,
    'h': help,
    'c': clear,
    't': selectTvShow,
    'o': OverView,
    'a': actors,
    'm': myFavourites,
    'f': favouriteThis,
    'd': deleteFavourites,
    # 'x': truct,
    'q': quit,
}

# =======================
#      MAIN PROGRAM
# =======================
# Tv Show Samples: Game of Thrones - stranger things - dexter - lost

# Main Program
if __name__ == "__main__":
    # Launch main menu
    main_menu()
