from browser import document as doc, window
from datetime import datetime
import json
import emoji
selected_file = None  # global variable to hold the file


def file_selected(ev):
    global selected_file
    selected_file = ev.target.files[0]


doc["fileInput"].bind("change", file_selected)


def handle_file(ev):
    global selected_file
    if not selected_file:
        alert("Please select a file first!")
        return

    reader = window.FileReader.new()

    def onload(e):
        data = json.loads(e.target.result)
        msg_count = int(data['messageCount'])

        addresses = []
        for i in range(msg_count):
            address = str(data['messages'][i].get('address', ""))

            # Skip placeholder token
            if address == 'insert-address-token':
                continue

            # Strip leading "+" from phone numbers
            if address.startswith("+"):
                address = address[1:]

            # Only add unique addresses
            if address not in addresses:
                addresses.append(address)

        output = ""
        prev_ts = None  # store previous message timestamp in seconds

        for i in range(msg_count):
            raw_address = str(data['messages'][i]['address'])
            if raw_address.startswith("+"):
                address = raw_address[1:]
            else:
                address = raw_address

            # Filter unwanted messages
            body_text = data['messages'][i]['body'].rstrip()
            if body_text == "" or address != str(doc["input-number"].value):
                continue

            # current timestamp (ms → seconds)
            ts = int(data['messages'][i]['date']) / 1000
            dt = datetime.fromtimestamp(ts)
            time_str = dt.strftime("%Y-%m-%d %H:%M:%S")

            # Compare with previous message
            if prev_ts is not None:
                delta_sec = ts - prev_ts
                if delta_sec > 600:  # example: gap > 1 hour
                    output += "                                 │\n"  # separator for big gaps

            prev_ts = ts  # update previous timestamp

            # wrap emojis
            body = emoji.wrap_emojis(
                body_text.replace("\r", "").replace("\n", ""))

            # determine sender
            if str(data['messages'][i]['type']) == '2':
                print_address = "<span class='you'>You</span>        "
                print_body = f"<span class='you-text'>{body}</span>"
            else:
                print_address = f"<span class='them'>{address}</span>"
                print_body = f"<span class='them-text'>{body}</span>"

            # append to output
            output += f"{time_str}  {print_address} │ {print_body}<br>"

        # str(datetime.fromtimestamp(int(data['messages'][0]['date'])/1000))     text.upper()
        doc["output"].html = output

    reader.bind("load", onload)
    reader.readAsText(selected_file)


doc["send-btn"].bind("click", handle_file)
