import json
import sys
from datetime import datetime
from utils.config import GENRIC
import os
import pandas as pd

class DataHandler():

    def __init__(self, clientID):
        self.clientID = clientID

        self.clientRootFolder = GENRIC.clientRootFolder.replace(GENRIC.replace_str, self.clientID)
        self.positionProcessedFile = os.path.join(self.clientRootFolder, GENRIC.positionProcessedFile)
        self.df = pd.read_csv(self.positionProcessedFile)

        self.debug = ''

    def getTableData(self):
        # Start building the HTML table
        retStr = '''
        <table class="table table-bordered">
            <thead class="thead-dark">
                <tr class="table-dark">
                    <th>Trading Symbol</th>
                    <th>Net Quantity</th>
                    <th>Unrealized MTOM</th>
                    <th>Realized PNL</th>
                </tr>
            </thead>
            <tbody>
        '''

        # Loop through each row in the DataFrame and add a table row for each
        totalPNL = 0.0
        for index, row in self.df.iterrows():
            realized_pnl = float("{:.2f}".format(row['RealizedPNL']))
            class_name = 'text-success' if realized_pnl > 0 else 'text-danger'
            
            # Treat netQuantity as integer and apply CSS class
            net_quantity = int(row['netQuantity'])
            net_quantity_class = 'text-danger' if net_quantity < 0 else 'text-nothing'

            totalPNL += realized_pnl

            retStr += f'''
                <tr>
                    <td>{row['tradingSymbol']}</td>
                    <td class="{net_quantity_class}">{net_quantity}</td>
                    <td>{row['unrealizedMTOM']}</td>
                    <td class="{class_name}">{realized_pnl}</td>
                </tr>
            '''

        # Add the total PNL row
        totalPNL_str = "{:.2f}".format(totalPNL)
        total_class_name = 'text-success' if totalPNL > 0 else 'text-danger'
        retStr += f'''
            <tr>
                <td colspan="3" class="text-center {total_class_name}"><strong>Total PNL</strong></td>
                <td class="{total_class_name}"><strong>{totalPNL_str}</strong></td>
            </tr>
        '''

        # Close the table
        retStr += '''
            </tbody>
        </table>
        '''

        print(retStr)





    def getDebug(self):
        return str(self.debug)



if __name__== "__main__":

    returnDict = {}
    returnDict['status'] = 'OK'
    returnDict['remarks'] = ''
    returnDict['data'] = ''

    helper = DataHandler(sys.argv[1])
    helper.getTableData()



    