# -*- coding: utf-8 -*-

# uiconcerts.py
# This file is part of qarte-5
#    
# Author: Vincent Vande Vyvre <vincent.vandevyvre@oqapy.eu>
# Copyright: 2018-2025 Vincent Vande Vyvre
# Licence: GPL3
# Home page: https://launchpad.net/qarte
#
# Arte Concert page

from PyQt5.QtCore import (Qt, QSize, QCoreApplication, pyqtSignal)
from PyQt5.QtGui import QImage, QPixmap, QIcon
from PyQt5.QtWidgets import (QWidget, QGridLayout, QSplitter,
                             QVBoxLayout, QHBoxLayout, QSizePolicy,
                             QTableWidget, QAbstractItemView, QLineEdit,  
                             QPlainTextEdit, QLabel, QPushButton, QToolButton,
                             QSpacerItem, QGraphicsView, QGraphicsScene,
                             QTableWidgetItem, QSlider)
from PyQt5.QtMultimedia import QMediaPlayer
from PyQt5.QtMultimediaWidgets import QGraphicsVideoItem, QVideoWidget

from .basket import Basket
from .concertsviewer import ConcertsViewer
from .downloadingwidgets import DownloadingWidgets
from .VWidgets_qt5.vlineedit import VLineEdit


class UiConcerts(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.ui = parent
        self.core = parent.core
        self.gridLayout = QGridLayout(self)
        self.gridLayout.setContentsMargins(0, 0, 0, 0)
        self.v_layout = QVBoxLayout()
        self.viewer = ConcertsViewer(parent, self)
        self.viewer.setMaximumSize(QSize(16777215, 270))
        self.v_layout.addWidget(self.viewer)
        self.h_layout = QHBoxLayout()
        self.v_layout1 = QVBoxLayout()
        self.v_layout1.setContentsMargins(0, 0, 0, 0)
        self.v_layout1.setSpacing(2)
        self.category_wdg = QWidget(self)
        self.category_wdg.setMaximumSize(QSize(16777215, 34))
        self.h_layout1 = QHBoxLayout(self.category_wdg)
        self.h_layout1.setContentsMargins(0, 0, 0, 0)

        self.v_layout1.addWidget(self.category_wdg)
        # Sorting widgets
        self.h_layout2 = QHBoxLayout()
        self.h_layout2.setContentsMargins(6, 2, 6, 2)
        self.filter_lbl = QLabel(self)
        self.filter_lbl.setText('Filter: ')
        self.h_layout2.addWidget(self.filter_lbl)
        self.filter_led = VLineEdit(self)
        #self.filter_led.setResetButton(True)
        self.filter_led.setHistoricButton(True)
        self.filter_led.setCommandButton(True)
        self.filter_led.setInformativeText(_('Enter a keyword'))
        icon = QIcon()
        icon.addPixmap(QPixmap("medias/magnifier_20x20.png"))
        self.filter_led.set_command_icon(icon)
        self.h_layout2.addWidget(self.filter_led)
        self.result_lbl = QLabel(self)
        self.h_layout2.addWidget(self.result_lbl)
        spacer = QSpacerItem(40, 20, QSizePolicy.Preferred, QSizePolicy.Minimum)
        self.h_layout2.addItem(spacer)
        self.file_name_lbl = QLabel(self)
        self.file_name_lbl.setText(_("File name:"))
        self.h_layout2.addWidget(self.file_name_lbl)
        self.file_name_led = QLineEdit(self)
        self.h_layout2.addWidget(self.file_name_led)
        self.v_layout1.addLayout(self.h_layout2)
        self.splitter = QSplitter(self)
        self.splitter.setOrientation(Qt.Horizontal)

        # Medias widget
        self.media_wdg = QWidget(self.splitter)
        self.media_layout = QHBoxLayout(self.media_wdg)
        self.media_layout.setContentsMargins(0, 0, 0, 0)
        self.thumbView = QGraphicsView(self)
        # Asked by an user with a little screen
        #self.thumbView.setMinimumSize(QSize(350, 120))
        #self.thumbView.setMaximumSize(QSize(16777215, 200))
        self.scene = QGraphicsScene()
        self.thumbView.setScene(self.scene)
        self.media_layout.addWidget(self.thumbView)
        self.player_wdg = QVideoWidget()
        self.media_layout.addWidget(self.player_wdg)
        self.player_wdg.hide()
        self.audio_wdg = QVideoWidget()
        self.media_layout.addWidget(self.audio_wdg)
        self.audio_wdg.hide()
        

        # Control widgets
        self.control_wdg = QWidget(self.media_wdg)
        self.control_wdg.setMaximumSize(150, 9999)
        self.v_layout2 = QVBoxLayout(self.control_wdg)
        self.start_btn = QPushButton(self.control_wdg)
        self.start_btn.setText(_("Play"))
        self.v_layout2.addWidget(self.start_btn)
        self.h_layout5 = QHBoxLayout()
        self.elapsed_lbl = QLabel(self.control_wdg)
        self.elapsed_lbl.setText("00:00:00")
        self.h_layout5.addWidget(self.elapsed_lbl)
        spacer = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.h_layout5.addItem(spacer)
        self.duration_lbl = QLabel(self.control_wdg)
        self.duration_lbl.setText("00:00:00")
        self.h_layout5.addWidget(self.duration_lbl)
        self.v_layout2.addLayout(self.h_layout5)
        self.h_layout6 = QHBoxLayout()
        space1 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.h_layout6.addItem(space1)
        self.level_ic = QLabel(self.control_wdg)
        self.level_ic.setPixmap(QPixmap("medias/sound.png"))
        self.h_layout6.addWidget(self.level_ic)
        self.level_lbl = QLabel(self.control_wdg)
        self.level_lbl.setAlignment(Qt.AlignRight|
                                    Qt.AlignTrailing|Qt.AlignVCenter)
        self.level_lbl.setText("50")
        self.h_layout6.addWidget(self.level_lbl)
        self.v_layout2.addLayout(self.h_layout6)
        self.level_sld = QSlider(self.control_wdg)
        self.level_sld.setOrientation(Qt.Horizontal)
        self.level_sld.setValue(50)
        self.v_layout2.addWidget(self.level_sld)
        self.pause_btn = QPushButton(self.control_wdg)
        self.pause_btn.setText(_("Pause"))
        self.v_layout2.addWidget(self.pause_btn)
        self.stop_btn = QPushButton(self.control_wdg)
        self.stop_btn.setText(_("Stop"))
        self.v_layout2.addWidget(self.stop_btn)
        space2 = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding)
        self.v_layout2.addItem(space2)
        self.media_layout.addWidget(self.control_wdg)

        # Versions table
        self.vers_twg = QualitiesTable(self, self.splitter)
        # Asked by an user with a little screen
        #self.vers_twg.setMinimumSize(500, 100)
        self.vers_twg.setRowCount(0)
        self.v_layout1.addWidget(self.splitter)
        self.h_layout.addLayout(self.v_layout1)
        self.v_layout3 = QVBoxLayout()
        self.live_basket = Basket(self, "Concert", self)
        self.live_basket.setMaximumSize(QSize(300, 16777215))
        self.v_layout3.addWidget(self.live_basket)
        self.dl_live_wdg = DownloadingWidgets(self)
        self.v_layout3.addWidget(self.dl_live_wdg)
        self.h_layout.addLayout(self.v_layout3)
        self.v_layout.addLayout(self.h_layout)
        self.editor_live = QPlainTextEdit(self)
        self.editor_live.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.editor_live.setStyleSheet("""background: qlineargradient(
                                        x1: 0, y1: 0, x2: 0, y2: 1,
                                        stop: 0 #FFFFFF, stop: 1 #EDEDED)""")
        self.v_layout.addWidget(self.editor_live)
        self.gridLayout.addLayout(self.v_layout, 0, 0, 1, 1)

    def configure(self, names):
        spacer1 = QSpacerItem(40, 20, QSizePolicy.Preferred, 
                                       QSizePolicy.Minimum)
        self.h_layout1.addItem(spacer1)
        self.category_buttons = []
        for idx, cat in enumerate(names):
            button = CategoryButton(idx, self, self)
            button.set_properties(cat, cat, cat)
            self.h_layout1.addWidget(button)
            self.category_buttons.append(button)
        spacer2 = QSpacerItem(40, 20, QSizePolicy.Preferred, 
                                       QSizePolicy.Minimum)
        self.h_layout1.addItem(spacer2)

    def set_active_category(self, index, action=False):
        for button in self.category_buttons:
            button.set_current(False)

        if action:
            # Called at startup
            self.category_buttons[index].click()

        else:
            self.category_buttons[index].set_current(True)

    def enable_current_button(self):
        """Set enabled the current category.

        Called when a sublist of videos is displayed.
        """
        for button in self.category_buttons:
            button.is_current = False

    def show_preview(self, path):
        self.scene.clear()
        size = self.thumbView.size()
        img = QImage(path)
        pix = QPixmap.fromImage(img.scaled(size.width()-2, 
                                          size.height()-2,
                                          Qt.KeepAspectRatio, 
                                          Qt.SmoothTransformation))
        self.scene.setSceneRect(0, 0, pix.width(), pix.height())
        self.scene.addPixmap(pix)
        self.pixmap = pix

    def add_video_to_download(self, quality):
        self.core.artelive.select_video_to_download(quality)

    def set_running_player(self):
        self.start_btn.setEnabled(False)
        self.pause_btn.setEnabled(True)
        self.stop_btn.setEnabled(True)

    def set_player_pause(self):
        self.start_btn.setEnabled(True)
        self.pause_btn.setEnabled(False)
        self.start_btn.setFocus(True)

    def stop_player(self):
        self.start_btn.setEnabled(True)
        self.pause_btn.setEnabled(False)
        self.stop_btn.setEnabled(False)
        self.elapsed_lbl.setText("00:00:00")
        self.duration_lbl.setText("00:00:00")

    def update_volume_slider(self, value):
        self.level_sld.blockSignals(True)
        self.level_sld.setValue(value)
        self.level_lbl.setText(str(value))
        self.level_sld.blockSignals(False)

    def resize_splitter(self):
        tot = self.splitter.sizes()[0] + self.splitter.sizes()[1]
        r = tot - 500
        self.splitter.setSizes([r, 500])

class CategoryButton(QPushButton):
    triggered = pyqtSignal(str)
    def __init__(self, idx, ui, parent=None):
        super().__init__(parent)
        self.idx = idx
        self.category = None
        self.de_tip = None
        self.fr_tip = None
        self.is_current = False
        self.ui = ui
        self.setMinimumSize(QSize(60, 30))
        self.setMaximumSize(QSize(1000, 30))
        #self.setFlat(True)
        self.setCheckable(True)
        self.clicked.connect(self.on_clicked)

    def set_properties(self, *prop):
        self.category = prop[0]
        self.setText(prop[0])
        self.fr_tip = prop[1]
        self.de_tip = prop[2]
        self.setStatusTip("{0} - {1}".format(self.fr_tip, self.de_tip))

    def set_current(self, b):
        if b:
            self.is_current = True
            icon = QIcon(QPixmap("medias/apply.png"))
            self.setIcon(icon)

        else:
            self.is_current = False
            icon = QIcon()
            self.setIcon(icon)

    def enterEvent(self, event):
        return
        self.ui.statusbar.showMessage(u"{0} - {1}"
                                        .format(self.fr_tip, self.de_tip))

    def leaveEvent(self, event):
        return

    def mousePressEvent(self, event):
        if not self.is_current:
            self.set_current(True)
            self.triggered.emit(self.category)

        event.ignore()

    def on_clicked(self):
        self.set_current(True)
        self.triggered.emit(self.category)

class QualitiesTable(QTableWidget):
    itemAdded = pyqtSignal(int)
    def __init__(self, ui, parent=None):
        super().__init__(parent)
        self.ui = ui
        self.setSelectionMode(QAbstractItemView.SingleSelection)
        self.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.verticalHeader().hide()
        self.setIconSize(QSize(85, 48))
        self.setColumnCount(4)
        self.setColumnWidth(0, 60)
        self.setColumnWidth(1, 120)
        self.setColumnWidth(2, 120)
        self.setColumnWidth(3, 48)
        self.setHorizontalHeaderLabels([_("Index"), _("Size"), "Bitrate",
                                         "Add"])

    def add_item(self, item):
        self.setHorizontalHeaderLabels([_("Index"), _("Size"), "Bitrate",
                                         "Add"])
        rc = self.rowCount()
        self.insertRow(rc)
        try:
            quality = item["id"]
        except KeyError:
            quality = "Unknow"

        try:
            w, h = item["resolution"]
            size = "%s x %s" %(w, h)
        except KeyError:
            size = "? x ?"

        try:
            bitrate = str(item["bandwidth"])
        except KeyError:
            bitrate = "?"

        qitem = QTableWidgetItem()
        qitem.setText(str(quality))
        self.setItem(rc, 0, qitem)
        sitem = QTableWidgetItem()
        sitem.setText(size)
        self.setItem(rc, 1, sitem)
        bitem = QTableWidgetItem()
        bitem.setText(bitrate)
        self.setItem(rc, 2, bitem)
        button = AddButton(quality, self.ui, self)
        self.setCellWidget(rc, 3, button)

    def show_warning(self, warn):
        self.setHorizontalHeaderLabels([_("Quality"), _("Size"), "Bitrate",
                                         "Version", "Add"])
        self.insertRow(0)
        qitem = QTableWidgetItem()
        qitem.setText(warn)
        self.setItem(0, 3, qitem)


class AddButton(QToolButton):
    def __init__(self, quality, driver, parent=None):
        super().__init__(parent)
        icon = QIcon(QPixmap("medias/plus_white_20x20.png"))
        self.setIcon(icon)
        self.quality = quality
        self.driver = driver
        self.clicked.connect(self.send_signal)

    def send_signal(self):
        self.setEnabled(False)
        self.driver.add_video_to_download(self.quality)

class Core:
    def __init__(self):
        self.categories = ["Musiques Actuelles", "Classique", "Opera",
                            "Jazz", "Musiques du Monde", "Arts Scéniques"]
if __name__ == "__main__":
    import sys
    core = Core()
    app = QApplication(sys.argv)
    MainWindow = QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(core, MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())

