import csv
import hashlib

import sys
import os
modules_paths = ['.', '../../../modules/']
for modules_path in modules_paths:
    if os.path.exists(modules_path):
        sys.path.insert(1, modules_path)

from messaging.MessageHandler import MessageHandler
from db.repository import Repository

# file to read the data from
CSV_FILE = r'dummy_upload\smart_energy\Energy_Dataset.csv'
handler = MessageHandler(Repository())


processed_transactions = []
def upload_transaction(transaction):
    '''{"type": "new-trace", 
    "content": {"use_case": "smart-energy", "table": "smart-energy", "id": "dd2c5146c919b046d77a32a5cf553d5133163562f7b7e1298c878c575d516025", 
    "properties": {"Customer": "297", "Energy_Consumption_kWh": "0.177", "Heating_Consumption_kWh": "0.0", "Latitude": "-33.362679", "Longitude": "151.447302", "Postcode": "2261", "Price_AUD_MWh": "58.05", "Solar_Production_kWh": "0.0", "Timestamp": "2013-06-30 00:00:00", "Total_Demand_MWh": "8154.14", "UniqueID": "dd2c5146c919b046d77a32a5cf553d5133163562f7b7e1298c878c575d516025"}
    }}'''
    uid = hashlib.sha256(f"{transaction['Customer']}{transaction['Timestamp']}".encode("utf-8")).hexdigest()
    transaction['UniqueID'] = uid
    t = {        
        'use_case': transaction['ApplicationType'],
        'table': transaction['docType'],
        'id': uid,
        'properties': transaction,
    }
    # handler.handle_new_trace(t)
    
    processed_transactions.append(t)


def store_transactions_for_mirsat():
    '''
    Stores the processed transactions as if they would be returned 
    by Trace Retrieval microservice after fixing the message queue bug.
    '''
    flattened_transactions = []
    for transaction in processed_transactions:
        transaction = transaction['properties']

        transaction['use_case'] = transaction['ApplicationType']
        del transaction['ApplicationType']

        transaction['table'] = transaction['docType']
        del transaction['docType']

        flattened_transactions.append(transaction)

    import json
    with open('flattened_smart_energy_data.json', 'w') as file:
        file.write(json.dumps(flattened_transactions))


if __name__ == '__main__':    
    with open(CSV_FILE, 'r') as file:
        reader = csv.reader(file)

        titles = next(reader)

        old_c = None
        for row in reader:
            transaction = {}
            transaction['ApplicationType'] = 'smart-energy'
            transaction['docType'] = 'smart-energy-paper'
            for idx in range(len(row)):
                transaction[titles[idx]] = row[idx]

            # also include the user demand, as Total_Demand_WMh is not per user
            energy_cons = float(transaction['Energy_Consumption_kWh']) if transaction['Energy_Consumption_kWh'] is not None and transaction['Energy_Consumption_kWh'] != "" else 0
            heating_cons = float(transaction['Heating_Consumption_kWh']) if transaction['Heating_Consumption_kWh'] is not None and transaction['Heating_Consumption_kWh'] != "" else 0
            transaction['User_Demand_kWh'] = heating_cons + energy_cons

            if transaction['Customer'] != old_c:      
                old_c = transaction['Customer']
                print(f"uploading for {old_c}")

            upload_transaction(transaction)

    store_transactions_for_mirsat()