#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 22 15:23:06 2025

@author: heikki
"""

# from browser.widgets.dialog import InfoDialog

from browser import document, window, websocket, html, aio, alert
from javascript import JSON
# import json
import mod_valikko


WS = None


# def play_video(video_file):
#     # print("video_file")
#     document['video'].src = video_file
#     document['video'].load()
#     document['video'].play()


######################################


class WebSocketClient:
    def __init__(self, url):
        self.url = url
        self.ws = None
        self.connect()

    def connect(self, event=None):
        """Connect to the WebSocket server."""
        try:
            # InfoDialog("", f"try to connect to {self.url}", remove_after=10)

            # alert(f"try to connetct to {self.url}")
            self.ws = websocket.WebSocket(self.url)

            # Set up event handlers
            self.ws.bind("open", self.on_open)
            self.ws.bind("message", self.on_message)
            self.ws.bind("close", self.on_close)
            self.ws.bind("error", self.on_error)

        except Exception as e:
            alert(f"Connection error: {e}", "error")

    def disconnect(self, event=None):
        """Disconnect from the WebSocket server."""
        if self.ws:
            self.ws.close()
            self.ws = None

    def on_open(self, event):
        """Handle WebSocket open event."""
        # InfoDialog("", "connected", remove_after=10)
        self.send_message({'type': 'albumit'})

    def on_message(self, event):
        """Handle incoming WebSocket messages."""
        try:
            data = JSON.parse(event.data)
            # InfoDialog("", data['type'], remove_after=10)
            # alert([data['type'], data['msg']])

            if data["type"] == "kuva":
                # alert('kuva tulossa')
                document['photo'].style.display = 'block'
                document['video'].style.display = 'none'
                document['otsikko'].innerHTML = data['otsikko']
                document['kuvaus'].innerHTML = data['kuvaus']
                document['progress'].innerHTML = data['progress']
                document['photo'].src = \
                    f'data:image/jpeg;base64,{data["src"]}'

            elif data["type"] == "video":
                video = document['video']
                video.style.display = 'block'
                document['photo'].style.display = 'none'
                video.src = data['video_src']
                video.load()  # forces the video to load the new source
                video.play()  # Start playing
                # play_video()

            elif data["type"] == "albumit":
                # InfoDialog("", "valinta alkaa", remove_after=10)
                valinta(
                   JSON.parse(data['albumit']),
                   JSON.parse(data['esittelyt']))

            elif data["type"] == "valmis":
                document.exitFullscreen()
                # self.disconnect()

            else:
                alert(['outo viesti ', data])

        except Exception as err:
            # If not JSON, just display the raw message
            alert(f"Server: {event.data}", "received", {err})

    def on_close(self, event):
        """Handle WebSocket close event."""
        # alert("Disconnected from the server")
        self.ws = None
        window.history.back()

    def on_error(self, event):
        """Handle WebSocket error event."""
        alert(f"Error: {event.data}")

    def send_message(self, message, event=None):
        """Send a message to the WebSocket server."""
        if self.ws and self.ws.readyState == 1:  # OPEN
            self.ws.send(JSON.stringify(message))
        else:
            alert("send_message: Not connected to server")

######################################################


def seis(evt=None):
    # InfoDialog("", "seis", remove_after=10)
    document['kehys'].style.display = "none"
    document['valikot'].style.display = 'block'
    WS.send_message({'type': 'seis'})


def lopeta(evt=None):
    # InfoDialog("", "lopeta", remove_after=10)
    WS.disconnect()
    window.close()
    # window.history.back()


def valinta(albumit, esittelyt, event=None):
    # alert(albumit)
    # alert(esittelyt)
    mod_valikko.valinnat_0(albumit, esittelyt)


def slideshow(event=None):
    # alert('fun slideshow')
    selected = [chbx.value for chbx in document.get(name='selected')
                if chbx.checked]
    if len(selected) == 0:
        alert("et valinnut mitään")
    else:
        viive = int(document['kuva_viive'].value)
        document['valikot'].style.display = 'none'
        document['kehys'].style.display = 'block'
        document['intro'].style.display = 'block'
        # document['seis'].style.display = 'block'
        document['kehys'].requestFullscreen()
        data = {
            "type": "valitut",
            "wait": viive,
            "valitut": selected
        }
        WS.send_message(data)


def video_valmis(evt=None):
    # InfoDialog("", "video_valmis", remove_after=10)
    WS.send_message({'type': 'OK'})


def kuva_valmis(evt=None):
    # InfoDialog("", "kuva_valmis", remove_after=10)
    WS.send_message({'type': 'OK'})


def start_btns():
    start = html.DIV(Class='flex-container')
    viivevalikko = html.DIV(Class='valikko')

    # viivevalikko <= viive('info_viive', "Kuva ja teksti näkyvissä") + ' '
    viivevalikko <= odotus(
        'kuva_viive', "Kuva näkyvissä vähintään sekuntia ") + ' '
    start <= viivevalikko

    b_show = html.BUTTON("Näytä valitut")

    b_show.bind("click", slideshow)
    start <= b_show
    document['start'] <= start
    document['start'].style.display = 'none'

    document['seis'].bind("click", seis)
    document['lopeta'].bind("click", lopeta)
    document['video'].bind("ended", video_valmis)
    document['photo'].bind("load", kuva_valmis)


def odotus(viive_id, selite):
    viive = html.SELECT(id=viive_id)
    viive <= html.OPTION('1s', value=1)
    viive <= html.OPTION('2s', value=2)
    viive <= html.OPTION('3s', value=3)
    viive <= html.OPTION('4s', value=4)
    viive <= html.OPTION('5s', value=5, selected=True)
    viive <= html.OPTION('6s', value=6)
    viive <= html.OPTION('8s', value=8)
    viive <= html.OPTION('10s', value=10)
    viive <= html.OPTION('15s', value=15)
    viive <= html.OPTION('20s', value=20)
    return html.SPAN(selite + ' ' + viive + ' ')


async def start_app():
    global WS
    # InfoDialog("start_app", "", remove_after=10)
    start_btns()
    # InfoDialog("", "start buttons ohitettu", remove_after=10)
    # document['seis'].style.display = 'none'
    # document['lopeta'].style.display = 'none'
    document['video'].style.display = 'none'
    document['kehys'].style.display = 'none'
    document['intro'].style.display = 'none'
    document['valikot'].style.display = 'block'

    if window.location.protocol == "https:":
        protocol = "wss:"
    else:
        protocol = "ws:"
    ws_url = f"{protocol}//{window.location.host}/ws"
    # InfoDialog("", ws_url, remove_after=10)
    WS = WebSocketClient(ws_url)


aio.run(start_app())
