import datetime
import pandas as pd
import plotly.graph_objects as go
from plotly.subplots import make_subplots
from xhtml2pdf import pisa    
from configparser import ConfigParser 
import os



# read config.ini file
config_object = ConfigParser()
config_object.read("/var/www/html/internal-tool/.config.ini")

# get info
savepathinfo = config_object["save_path"]


def plot_graph(df1, df2, df3, df4, df5, yesterday_date):
    df3['reason'] = 'Wrong number length'
    df5['reason'] = 'Operator failed to reach handset'
    savepath = os.path.join(savepathinfo["summary_path"], f"report-{yesterday_date}.html")

    with open(savepath, 'a') as f:

        fig = go.Figure(make_subplots(rows=5, cols=1, specs=[[{'type' : 'domain'}],
                                                            [{'type'  : 'domain'}],
                                                            [{'type'  : 'domain'}],
                                                            [{'type'  : 'table'}], 
                                                            [{'type'  : 'table'}]],

                                    subplot_titles=(
                                        "GENERAL DLR STATUSES", 
                                        "UNDELIVERED COUNTS BY NETWORKS", 
                                        "EXPIRED COUNTS BY NETWORKS",
                                        "UNDELIVERED MSISDN",
                                        "EXPIRED MSISDN")))
        fig.add_trace(
            go.Pie(
                labels=df1['status'].tolist(), values=df1['count'].tolist()
            ), row=1, col=1
        )

        fig.add_trace(
            go.Pie(
                labels=df2['network'].tolist(), values=df1['count'].tolist()
            ), row=2, col=1
        )

        fig.add_trace(
            go.Pie(
                labels=df4['network'].tolist(), values=df1['count'].tolist()
            ), row=3, col=1
        )
        fig.add_trace(
            go.Table(
                header=dict(values=['msisdn', 'reason']),
                cells=dict(values=[df3['msisdn'].tolist(), df3['reason'].tolist()])
            ), row=4, col=1
        )

        fig.add_trace(
            go.Table(
                header=dict(values=['msisdn', 'reason']),
                cells=dict(values=[df5['msisdn'].tolist(), df5['reason'].tolist()])
            ), row=4, col=1
        )
        
        fig.update_layout(
                height=800, width=800
              )
        f.write(fig.to_html(full_html=False, include_plotlyjs='cdn'))
    # save path
    return savepath


    


def convert2Pdf(source_html, output_filename):
    result_file = open(output_filename, "w+b")

    # convert HTML to PDF
    pisa_status = pisa.CreatePDF(source_html, dest=result_file)                                                 
    
    # close output file
    result_file.close()             

    # return True on success and False on errors
    return pisa_status.err
   

        
