"""
@file File Documentation
"""
import pandas as pd
import csv
from mlxtend.frequent_patterns import association_rules
import matplotlib.pyplot as plt
from mlxtend.preprocessing import TransactionEncoder
from mlxtend.frequent_patterns import apriori
from mlxtend.frequent_patterns import association_rules
from collections import Counter
from IPython.display import HTML
import numpy as np


def genreCount(genre_year_divide1):
    """!genreCount() is a function used to give the count of Genre from the given input data

    @param genre_year_divide1: input data
    """
    ##genre_year_divide2: columns releaseYear, Genre_Name, Genre_Value are identifier variables, while all other columns, considered measured variables, are unpivoted to the row axis, variable and value.
    genre_year_divide2 = pd.melt(genre_year_divide1, id_vars=['releaseYear'], var_name='Genre_Name', value_name='Genre_Value')
    genre_year_divide2.drop('Genre_Name',axis=1,inplace=True)
    genre_year_divide2 = genre_year_divide2.dropna()

    ##genre_year_divide3: contains data grouped by ```releaseYear```
    genre_year_divide3 = genre_year_divide2.groupby('releaseYear')
    genre_year_divide4 = pd.DataFrame(columns=genre_year_divide2.columns)
    for i,j in genre_year_divide3:
        genre_year_divide4 = pd.concat([genre_year_divide4,j],ignore_index=True)
    

    genre_year_divide4['Genre_Value'].value_counts()
    ##genre_year_divide8: contains data grouped by *releaseYear* & *releaseYear*
    genre_year_divide8 = genre_year_divide4.groupby(['Genre_Value','releaseYear'])
    y = pd.DataFrame()
    l = []
    for a,b in genre_year_divide8:
        l.append({'Genre':a[0],'Year':a[1],'Count':b['Genre_Value'].count()})
    y = pd.DataFrame(l)
    y = y.set_index('Genre')
    getActors(genre_year_divide1)


def getActors(genre_year_divide1):
    """!getActors() function is used to give the list of actors in the data provided 

    @param genre_year_divide: input data
    """
    ##movie_data: contains the CSV file as read value
    movie_data = pd.read_csv('files/BollywoodMovieDetail.csv')
    ##actor: contains actors name and index corresponding to the names
    actor = movie_data['actors']
    actor.dropna()
    actor = actor.reset_index(drop=True)
    x = []
    for i in range(len(actor)):
        a = str(actor[i]).split('|')
        a = [z.strip() for z in a]
        x.append(a)
    ##actor_devide: heterogeneous tabular data structure with labeled axes
    actor_divide = pd.DataFrame(x,columns=['Actor 1','Actor 2','Actor 3','Actor 4'])
    linkGenre(actor_divide,genre_year_divide1)
    
def linkGenre(actor_divide,genre_year_divide1):
    """!linkGenre() fuction is used to give the actors linked with the corresponding genres

    @param actor_divide: input data for actor names
    @param genre_year_divide1: input data for year
    """
    ##actor_genre_divide: concatted value of actors with the genre by column 
    actor_genre_divide = actor_divide
    temp_genre = genre_year_divide1.loc[:,'Genre 1':'Genre 3']
    actor_genre_divide = pd.concat([actor_divide,temp_genre],axis=1)
    actor_genre_divide = actor_genre_divide.loc[:,'Actor 1':'Genre 3']
    actor_genre_divide.head(20)

    genre_input = 'comedy'
    a1 = actor_genre_divide[actor_genre_divide['Genre 1'] == genre_input.capitalize()]
    a2 = actor_genre_divide[actor_genre_divide['Genre 2'] == genre_input.capitalize()]
    a3 = actor_genre_divide[actor_genre_divide['Genre 3'] == genre_input.capitalize()]
    taking_all = a1.append(a2, ignore_index=True).append(a3, ignore_index=True)


    test = np.array(taking_all[['Actor 1', 'Actor 2', 'Actor 3', 'Actor 4']])
    test[0]

    '''
    te = TransactionEncoder()
    te = te.fit(test)
    te_ary = te.transform(test)
    '''


    df=pd.melt(actor_genre_divide,id_vars=["Genre 1","Genre 2","Genre 3"],var_name="Actor",value_name="Value")


    df.columns=['Genre 1', 'Genre 2', 'Genre 3', 'Actor', 'Actor_name']
    df=df.drop(["Actor"],axis=1)
    df.columns
    df.columns=['Genre 1', 'Genre 2', 'Genre 3', 'Actor']
    df2=pd.melt(df,id_vars=["Actor"],var_name="Genre",value_name="Genre_Name")
    df2=df2.drop(["Genre"],axis=1)
    df2.columns=["Actor","Genre"]
    Data_actor_genre=df2
    Data_actor_genre
    actor_genre_divide_final = df2
    actor_genre_divide_final =  actor_genre_divide_final.dropna()

    actor_genre_divide_final.to_csv('files/ActorsWithGenre.csv', )
    t = actor_genre_divide_final.groupby(['Genre'])
    t.get_group('Romance')
    u = list(pd.unique(actor_genre_divide_final['Genre']))
    topActors(u,t)


    

def topActors(u,t):
    """!topActors() function gives the best possible top actors in a genre. *In this function we are saving top 10 actors for each genre in a CSV file*
    """
    ##xyz: it is a list that has the top 10 actors for a particular genre
    xyz = []
    for each in u:
        xyz.append(Counter(list(t.get_group(each)['Actor'])).most_common(10))


    d1 = {'Genre' : u, 'Top 10 Actors':xyz}
    ##df100: used to store the top 10 actors from each genre and to write in a CSV file
    df100 = pd.DataFrame(data = d1)
    df100 = df100.drop([21])
    df100.dropna()
    df100.to_csv('files/Aditya.csv')

def getGenre():
    """!getGenre() function is giving the genre of the particular actors  by reading the file BollywoodMovieDetail.csv and classifying them based on genre
    """
    plt.rcParams['figure.figsize'] = [15,10]

    ##movie_data: gets the file BollywoodMovieDetail.csv
    movie_data = pd.read_csv('files/BollywoodMovieDetail.csv')
    ##genre_divide: gets the genre from the input file in movie_data
    genre_divide = movie_data['genre']
    genre_divide.unique()
    genre_divide = movie_data[movie_data['genre'].isna()==False]
    genres = movie_data['genre']
    G = []
    for i in range(len(genres)):
        a = str(genres[i]).split('|')
        a = [z.strip() for z in a]
        G.append(a)
    splitGenre(G,genre_divide)
   
def splitGenre(G,genre_divide):
    """!splitGenre() function is used to split the genres of all the actors in multiple genres if he/she worked in multiple genres
    """
    ##genres: takes identifier values Genre 1, Genre 2, Genre 3 as columns and separate them 
    genres = pd.DataFrame(G,columns = ['Genre 1','Genre 2','Genre 3'])
    #genres = genres.dropna()
    big_genre_divide = pd.concat([genre_divide,genres],axis=1)

    ##genre1: has the value Genre 1
    genre1 = genres['Genre 1']
    ##genre2: has the value Genre 2
    genre2 = genres['Genre 2']
    ##genre3: has the value Genre 3
    genre3 = genres['Genre 3']
    genre1 = [i for i in genre1]
    genre2 = [i for i in genre2]
    genre3 = [i for i in genre3]
    ##Genre: has the concattenated value of all 3 genres
    Genre = genre1+genre2+genre3
    ##Genre2: has the identifier value genre
    Genre2 = pd.DataFrame(Genre,columns=['genre'])
    ##Genre3: has the counts of each genre
    Genre3 = pd.DataFrame(Genre2['genre'].value_counts())

    ##genre_year_divide1: has the saperated value of releaseYear, Genre 1, Genre 2, Genre 3
    genre_year_divide = big_genre_divide
    genre_year_divide1 = genre_year_divide[['releaseYear','Genre 1','Genre 2','Genre 3']]
    genreCount(genre_year_divide1)
    #genre_year_divide1.dropna()
    #genre_year_divide1

    

    # # Giving genres to actors

getGenre()

'''
    a = actor_genre_divide_final.groupby(['Actor'])
    b = list(pd.unique(actor_genre_divide_final['Actor']))

    aba = []
    for each in b:
        aba.append(Counter(list(a.get_group(each)['Genre'])).most_common(3))

    data = {'Actor':b,'Top Genres':aba}
    fin = pd.DataFrame(data=data)
    fin.head()

    fin.shape

    fin.to_csv('files/TopGenres.csv')

    te = TransactionEncoder()
    te = te.fit(x)
    te_ary = te.transform(x)


    df = pd.DataFrame(te_ary,columns=te.columns_)
    print("adfadsf")


    print("adfadsf")

    #rules = association_rules(romance,metric='confidence',min_threshold=0.001)
    input_genre = 'Romance'
    abascus = list(df100[df100['Genre'] == input_genre]['Top 10 Actors'])
    top_actor = (abascus[0][0][0])
    #rules[rules['antecedants'].apply(lambda x:set([top_actor]).issubset(x))]


    another = big_genre_divide.drop(columns = ['imdbId', 'title', 'releaseYear', 'releaseDate','writers','directors','sequel','hitFlop'])
    another = another.drop(columns = ['genre'])

    another.head()
    another.to_csv('files/castgenre.csv')

    genre_input = 'romance'
    a1 = another[another['Genre 1'] == genre_input.capitalize()]
    a2 = another[another['Genre 2'] == genre_input.capitalize()]
    a3 = another[another['Genre 3'] == genre_input.capitalize()]
    c = a1.append(a2, ignore_index=True).append(a3, ignore_index=True)
    print(c)
    genre_actors = c['actors']
    actor = movie_data['actors']
    actor.dropna()
    actor = actor.reset_index(drop=True)
    x = []
    for i in range(len(actor)):
        a = str(actor[i]).split('|')
        a = [z.strip() for z in a]
        x.append(a)
        

    te = TransactionEncoder()
    te = te.fit(x)
    te_ary = te.transform(x)
    print(te_ary)

    romance = pd.read_csv('files/romance.csv')

    print(romance)
    eval(romance['itemsets'][0])


    '''
