import json
import threading
import subprocess
from datetime import date, datetime

from emailer import email_sender
from zBSE_fetch import prev_close_updaterBSE, bse_fetcher
from zNSE_fetch import prev_close_updaterNSE, nse_fetcher
from z_getBSEdata import getBSEdata
from z_getNSEdata import getNSEdata
from z_auth_token import verify_auth

# Update zerodha credentials
def update_zerodha_creds(enctoken=None, websocket=None):
    # 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

    # Add the last updated date
    data["last_updated_on"] = str(datetime.today())

    # 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

# Threading fucntion
def run_in_threads(target1, target2):
    thread1 = threading.Thread(target=target1)
    thread2 = threading.Thread(target=target2)

    thread1.start()
    thread2.start()

    thread1.join()
    thread2.join()

# Get The Access Token
verify_auth()

# If required add credentials manually
# update_zerodha_creds()

# Run the threads for different tasks
run_in_threads(nse_fetcher, bse_fetcher)
run_in_threads(prev_close_updaterNSE, prev_close_updaterBSE)
run_in_threads(getNSEdata, getBSEdata)

# Send E-mail
email_sender()

print("Both NSE and BSE data fetching complete.")