# -*- coding: utf-8 -*-



"""



Created on Sun Jan 26 11:14:23 2020







@author: Edouard Machenaud



"""







import pandas as pd



import os



import glob











def loader(path_mov_file):



    df = pd.read_csv(path_mov_file, sep=';', encoding='ANSI')







    # Distinction between two types of mvt files



    if 'MANDAT' in os.path.basename(path_mov_file):



        columns = ['x', 'Depositaire', 'Date operation', 'x', 'Type actif', 'ISIN',



                   'x', 'Libelle valeur', 'x', 'x', 'Sens', 'Quantite',



                   'Cours en devise', 'Montant brut', 'Devise montant brut', 'x', 'x', 'x', 'x', 'x']



    else:



        columns = ['x', 'Depositaire', 'Date operation', 'Type actif', 'ISIN', 'Libelle valeur',



                   'Sens', 'Quantite', 'Cours en devise', 'Devise montant brut', 'Montant brut', 'x']







    df = pd.DataFrame(df.values, columns=columns)



    df.pop('x')



    df.fillna('?')



    df = df.join(pd.Series(['' for k in range(df.shape[0])], name='Nom Compagnie'))



    return (df)











def report_builder(path_mov, path_listing, path_rapport):



    # Get all movements files



    mov_files = glob.glob(os.path.join(path_mov, '*.csv'))



    # Load listing file



    file_listing = glob.glob(os.path.join(path_listing,'*.xlsx'))



    df_listing = pd.read_excel(file_listing[0])







    # list_company = df_listing['Nom Compagnie'].unique()



    # list_isin = df_listing['ISIN'].unique()







    # Concatenate all movements files



    concat_df = pd.DataFrame(columns=['Depositaire', 'Date operation', 'Type actif', 'ISIN',



                   'Libelle valeur', 'Sens', 'Quantite',



                   'Cours en devise', 'Montant brut', 'Devise montant brut'])







    for path_mov_file in mov_files:



        df = loader(path_mov_file)



        # Get and add company name



        for i in range(df.shape[0]):



            line_listing = df_listing.query('ISIN == ' + '"' + str(df.ISIN[i]) + '"')



            try:



                comp_name = line_listing['Nom Compagnie'].values[0]



                # fund_name = line_listing['Nom Fond'].values[0] ALREADY IN MOVEMENT FILES



            except IndexError:



                comp_name = 'XXX Not in listing'



            df['Nom Compagnie'][i] = comp_name



        concat_df = concat_df.append(df, ignore_index=True)



    concat_df.to_excel(path_rapport + 'Rapport_trim_mouvements.xlsx')