import json
import time
from datetime import date
from haralyzer import HarParser
from pymongo import MongoClient

client = MongoClient("mongodb://192.168.31.175:27017/")
database = client["zerodha_test"]
collection = database["zerodha_credentials"]

# Update zerodha credentials
def update_zerodha_creds(enctoken=None, websocket=None):
    # Operation to store MongoDB Credentials
    collection.insert_one({ "enctoken": str(enctoken), "websocket": str(websocket), "date": str(date.today()) })

    # Step 1: Load the existing JSON data
    with open('zerodha\credentials.json', 'r') as file:
        data = json.load(file)

    # Step 2: Update the local Zerodha credentials if input is provided
    if enctoken is not None:
        data["local"]["zerodha_creds"]["enctoken"] = enctoken
    if websocket is not None:
        data["local"]["zerodha_creds"]["websocket"] = websocket

    # Step 3: Update the live Zerodha credentials if input is provided
    if enctoken is not None:
        data["live"]["zerodha_creds"]["enctoken"] = enctoken
    if websocket is not None:
        data["live"]["zerodha_creds"]["websocket"] = websocket

    # Step 4: Write the updated data back to the file
    with open('zerodha\credentials.json', 'w') as file:
        json.dump(data, file, indent=4)  # Use indent=4 for a pretty-printed JSON file

def get_data(har_parser_data) -> None:
    """
    Parses the HAR data and extracts the WebSocket URL and enctoken.
    """
    while True:
        # Parse HAR File to JSON Format
        try:
            har_parser = HarParser(har_parser_data)
        except Exception as e:
            print(f"Some Error Occurred while parsing HAR: {e}")
            return

        # Extract HAR data and display its datatype
        data = har_parser.har_data
        print("Datatype of HAR converted >>>", type(data))

        # Filter HAR file entries that contain "ws.zerodha.com"
        filtered_entries = [entry for entry in data['entries'] if 'ws.zerodha.com' in entry['request']['url']]

        if not filtered_entries:
            raise ValueError("No WebSocket entries found in the HAR data.")

        filtered_har = {
            'log': {
                'version': data['version'],
                'creator': data['creator'],
                'entries': filtered_entries
            }
        }

        # WebSocket URL
        socket_url = filtered_har['log']['entries'][0]['request']['url']
        websocket_url = socket_url.replace("https", "wss")

        # Extract enctoken
        token = filtered_har['log']['entries'][0]['request']['queryString']
        enctoken = next((match_t['value'] for match_t in token if match_t['name'] == "enctoken"), None)

        if enctoken is None:
            raise ValueError("enctoken not found in the HAR data.")

        """
            Old Approach:
            -----------------------------------------------------------
            output_dict = {
                "websocket_url": websocket_url,
                "enctoken": enctoken
            }
            with open("zerodha\credentials.json", "w", encoding="utf-8") as f:
                json.dump(output_dict, f, indent=4)
        """

        # Write to zerodha\credentials.json
        update_zerodha_creds(enctoken=enctoken, websocket=websocket_url)


        print("WebSocket URL and enctoken saved successfully.")
        time.sleep(5)  # Adjust the sleep time based on your use case
        break
