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

# tvdownloadingconfig.py
# This file is part of qarte-5
#    
# Author: Vincent Vande Vyvre <vincent.vandevyvre@oqapy.eu>
# Copyright: 2012-2022 Vincent Vande Vyvre
# Licence: GPL3
# Home page: https://launchpad.net/qarte
#
# Download config dialog

import logging
lgg = logging.getLogger(__name__)

from PyQt5.QtCore import (Qt, QCoreApplication, QItemSelectionModel)
from PyQt5.QtGui import (QFont, )
from PyQt5.QtWidgets import (QDialog, QGridLayout, QVBoxLayout, QHBoxLayout,
                             QSpacerItem, QSizePolicy, QLabel, QLineEdit,
                             QCheckBox, QRadioButton, QButtonGroup, QFrame, 
                             QTableWidget, QTableWidgetItem, QAbstractItemView,
                             QPushButton, QApplication)

_ = str

class TvDownloadingConfig(QDialog):
    def __init__(self, driver, parent=None):
        super().__init__(parent)
        self.driver = driver
        self.resize(605, 686)
        self.gridLayout = QGridLayout(self)
        self.verticalLayout = QVBoxLayout()
        self.horizontalLayout = QHBoxLayout()
        self.filename_lbl = QLabel(self)
        self.horizontalLayout.addWidget(self.filename_lbl)
        self.filename_led = QLineEdit(self)
        self.horizontalLayout.addWidget(self.filename_led)
        self.verticalLayout.addLayout(self.horizontalLayout)
        self.horizontalLayout_2 = QHBoxLayout()
        self.replace_space_chb = QCheckBox(self)
        self.horizontalLayout_2.addWidget(self.replace_space_chb)
        self.underscore_rdo = QRadioButton(self)
        self.underscore_rdo.setEnabled(False)
        self.underscore_rdo.setChecked(True)
        self.horizontalLayout_2.addWidget(self.underscore_rdo)
        self.hyphen_rdo = QRadioButton(self)
        self.hyphen_rdo.setEnabled(False)
        self.horizontalLayout_2.addWidget(self.hyphen_rdo)
        self.buttonGroup_0 = QButtonGroup(self)
        self.buttonGroup_0.addButton(self.underscore_rdo)
        self.buttonGroup_0.addButton(self.hyphen_rdo)
        self.verticalLayout.addLayout(self.horizontalLayout_2)
        self.horizontalLayout_3 = QHBoxLayout()
        self.date_chb = QCheckBox(self)
        self.horizontalLayout_3.addWidget(self.date_chb)
        sp = QSpacerItem(328, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.horizontalLayout_3.addItem(sp)
        self.verticalLayout.addLayout(self.horizontalLayout_3)
        self.horizontalLayout_4 = QHBoxLayout()
        self.versions_lbl = QLabel(self)
        self.horizontalLayout_4.addWidget(self.versions_lbl)
        sp1 = QSpacerItem(288, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.horizontalLayout_4.addItem(sp1)
        self.verticalLayout.addLayout(self.horizontalLayout_4)
        self.horizontalLayout_5 = QHBoxLayout()
        self.videos_lbl = QLabel(self)
        self.horizontalLayout_5.addWidget(self.videos_lbl)
        sp2 = QSpacerItem(308, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.horizontalLayout_5.addItem(sp2)
        self.verticalLayout.addLayout(self.horizontalLayout_5)
        self.videos_tbl = VersionTable(0, self)
        self.verticalLayout.addWidget(self.videos_tbl)
        self.horizontalLayout_6 = QHBoxLayout()
        self.audio_lbl = QLabel(self)
        self.horizontalLayout_6.addWidget(self.audio_lbl)
        sp3 = QSpacerItem(308, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.horizontalLayout_6.addItem(sp3)
        self.verticalLayout.addLayout(self.horizontalLayout_6)

        self.horizontalLayout_9 = QHBoxLayout()
        self.audio_0_rdo = QRadioButton(self)
        self.horizontalLayout_9.addWidget(self.audio_0_rdo)
        self.audio_1_rdo = QRadioButton(self)
        self.horizontalLayout_9.addWidget(self.audio_1_rdo)
        self.buttonGroup_1 = QButtonGroup(self)
        self.buttonGroup_1.addButton(self.audio_0_rdo)
        self.buttonGroup_1.addButton(self.audio_1_rdo)
        self.buttonGroup_1.setId(self.audio_0_rdo, 0)
        self.buttonGroup_1.setId(self.audio_1_rdo, 1)
        self.verticalLayout.addLayout(self.horizontalLayout_9)
        self.horizontalLayout_10 = QHBoxLayout()
        self.subtitle_lbl = QLabel(self)
        self.horizontalLayout_10.addWidget(self.subtitle_lbl)
        sp4 = QSpacerItem(308, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.horizontalLayout_10.addItem(sp4)
        self.verticalLayout.addLayout(self.horizontalLayout_10)
        self.horizontalLayout_11 = QHBoxLayout()
        self.subtitles_0_rdo = QRadioButton(self)
        self.horizontalLayout_11.addWidget(self.subtitles_0_rdo)
        self.subtitles_1_rdo = QRadioButton(self)
        self.horizontalLayout_11.addWidget(self.subtitles_1_rdo)
        self.subtitles_2_rdo = QRadioButton(self)
        self.horizontalLayout_11.addWidget(self.subtitles_2_rdo)

        self.buttonGroup_2 = QButtonGroup(self)
        self.buttonGroup_2.addButton(self.subtitles_0_rdo)
        self.buttonGroup_2.addButton(self.subtitles_1_rdo)
        self.buttonGroup_2.addButton(self.subtitles_2_rdo)
        self.buttonGroup_2.setId(self.subtitles_0_rdo, 0)
        self.buttonGroup_2.setId(self.subtitles_1_rdo, 1)
        self.buttonGroup_2.setId(self.subtitles_2_rdo, 2)
        self.verticalLayout.addLayout(self.horizontalLayout_11)

        font = QFont()
        font.setFamily("DejaVu Sans")
        font.setWeight(75)
        font.setBold(True)
        self.choice_lbl = QLabel(self)
        self.choice_lbl.setText("")
        self.choice_lbl.setFont(font)
        self.verticalLayout.addWidget(self.choice_lbl)
        self.horizontalLayout_7 = QHBoxLayout()
        self.choice_chb = QCheckBox(self)
        self.horizontalLayout_7.addWidget(self.choice_chb)
        sp4 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.horizontalLayout_7.addItem(sp4)
        self.verticalLayout.addLayout(self.horizontalLayout_7)
        self.horizontalLayout_8 = QHBoxLayout()
        #self.no_merge_chb = QCheckBox(self)
        #self.horizontalLayout_8.addWidget(self.no_merge_chb)
        sp5 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.horizontalLayout_8.addItem(sp5)
        self.close_btn = QPushButton(self)
        self.horizontalLayout_8.addWidget(self.close_btn)
        self.verticalLayout.addLayout(self.horizontalLayout_8)
        self.gridLayout.addLayout(self.verticalLayout, 0, 0, 1, 1)
        self.languages = {"VF": "Français", "VOF": "Version originale française",
                          "VA": "Deutsch", "VOA": "Deutsch"}

        self.retranslateUi()
        self.replace_space_chb.stateChanged.connect(self.on_replace_checked)
        self.underscore_rdo.toggled.connect(self.set_separator)
        self.date_chb.stateChanged.connect(self.on_date_checked)
        self.choice_chb.stateChanged.connect(self.on_default_choice_changed)
        self.close_btn.clicked.connect(self.closeEvent)

    def retranslateUi(self):
        self.setWindowTitle(_("Downloading Parameters"))
        self.filename_lbl.setText(_("File name:"))
        self.replace_space_chb.setText(_("Replace space with:"))
        self.underscore_rdo.setText(_("Underscore"))
        self.hyphen_rdo.setText(_("Hyphen"))
        self.date_chb.setText(_("Add date"))
        self.versions_lbl.setText(_("Available versions:"))
        self.videos_lbl.setText(_("Videos:"))
        self.audio_lbl.setText(_("Audios:"))
        self.subtitle_lbl.setText(_("Subtitle"))
        self.subtitles_0_rdo.setText(_("No subtitle"))
        self.choice_chb.setText(_("Always use this quality / version"))
        #self.no_merge_chb.setText(_("Don't merge video, audio and subtitles"))
        self.close_btn.setText(_("Close"))

    def configure(self, video, quality, lang, date=True, subtitle=False):
        lgg.info("Config downloading lang: %s, quality: %s" 
                 %(lang, video.quality))
        if video.quality["is_hls"]:
            self.fix_video_name(video.streams)
            self.choice_chb.setEnabled(False)
            #self.no_merge_chb.setEnabled(False)
            #return

        self.video = video
        self.sep = " "
        self.current_item = None
        self.preffered = None
        lang1, lang2 = "Français", "Allemand"
        if lang == "de":
            lang1, lang2 = "Deutsch", "Fransozich"

        self.filename_led.setText(video.fname)
        first = lang1.lower()
        scnd = lang2.lower()
        vos = ("Originalfassung", "Version originale")
        self.videos_tbl.populate_table(video.streams[0])
        self.set_language_options(video.streams)

        self.select_default_quality(video.streams[0], video.quality,
                                    video.streams[1][0]["lang"])

    def set_language_options(self, options):
        audios = options[1]
        self.audio_0_rdo.setText(audios[0]["lang"])
        self.audio_0_rdo.setChecked(True)
        if len(audios) > 1:
            self.audio_1_rdo.setText(audios[1]["lang"])

        if len(audios) > 2:
            place = 2
            for a in audios[2:]:
                rbtn = QRadioButton(self)
                rbtn.setText(a["lang"])
                self.horizontalLayout_9.insertWidget(place, rbtn)
                self.buttonGroup_1.addButton(rbtn)
                self.buttonGroup_1.setId(rbtn, place)
                place += 1

        subts = options[2]
        self.subtitles_0_rdo.setChecked(True)

        if len(subts):
            txt = subts[0]["lang"]
            self.subtitles_1_rdo.setText(txt)
            if "forcé" in txt or "automatische" in txt:
                self.subtitles_1_rdo.setChecked(True)

        if len(subts) > 1:
            place = 2
            for a in subts[1:]:
                rbtn = QRadioButton(self)
                txt = a["lang"]
                rbtn.setText(txt)
                self.horizontalLayout_11.insertWidget(place, rbtn)
                self.buttonGroup_2.addButton(rbtn)
                self.buttonGroup_2.setId(rbtn, place)
                if self.video.subtitle == a:
                    rbtn.setChecked(True)
                elif "forcé" in txt or "automatische" in txt:
                    self.subtitles_1_rdo.setChecked(True)
                place += 1

    def fix_video_name(self, streams):
        for key in streams:
            for item in streams[key]:
                if item["name"] is None:
                    item["name"] = key

    def display_hls_streams(self, video):
        self.video = video
        self.sep = " "
        self.filename_led.setText(video.fname)
        self.videos_lbl.setText("All languages")
        for lang in video.streams:
            self.videos_tbl.populate_table(video.streams[lang])

    def select_default_quality(self, items, quality, version):
        item = None
        preffered = True
        size = quality["resolution"][1]
        for idx, i in enumerate(items):
            if i["resolution"][1] == size:
                item = idx
                break

        if item is None:
            item = 0
            i = items[0]
            preffered = False

        self.videos_tbl.set_selection(item)
        self.choice_chb.blockSignals(True)
        self.choice_chb.setChecked(preffered)
        self.choice_chb.blockSignals(False)
        txt = "%s x %s %s" %(i["resolution"][0], i["resolution"][1], version)
        self.choice_lbl.setText(txt)
        self.current_item = item
        if preffered:
            self.preffered = item

    def on_selection_changed(self, item):
        lgg.info("Item selected: %s" %(item))
        self.choice_chb.blockSignals(True)
        self.choice_chb.setChecked(False)
        self.choice_chb.setEnabled(False)
        self.choice_chb.blockSignals(False)

        self.current_item = item
        i = self.video.streams[0][item]
        txt = "%s x %s" %(i["resolution"][0], i["resolution"][1])
        self.choice_lbl.setText(txt)

    def on_replace_checked(self, state):
        self.underscore_rdo.setEnabled(state)
        self.hyphen_rdo.setEnabled(state)
        if state:
            self.set_separator()

        else:
            self.filename_led.setText(self.video.fname)
            self.sep = " "

    def set_separator(self):
        sep = "" + ("_" if self.underscore_rdo.isChecked() else "-")
        self.filename_led.blockSignals(True)
        self.filename_led.setText(self.filename_led.text()
                                    .replace(self.sep, sep))
        self.sep = sep
        self.filename_led.blockSignals(False)

    def on_date_checked(self, state):
        suffix = ""
        if state:
            suffix = "-" + self.video.date.strip("'\" ")
            suffix = suffix.replace(":", "-")
        self.filename_led.blockSignals(True)
        self.filename_led.setText(self.video.fname+suffix)
        self.filename_led.blockSignals(False)

    def on_default_choice_changed(self, state):
        if state:
            self.preferred = self.current_item[1]

    def closeEvent(self, event=None):
        self.video.fname = self.filename_led.text()
        item = self.videos_tbl.currentRow()
        self.video.quality = self.video.streams[0][item]
        audio = self.video.streams[1][self.buttonGroup_1.checkedId()]
        self.video.audio = audio
        sub = self.buttonGroup_2.checkedId()
        if not sub:
            self.video.subtitle = None

        else:
            self.video.subtitle = self.video.streams[2][sub-1]

        if self.choice_chb.isChecked():
            size = self.video.quality['resolution'][1]
            self.driver.set_preferred_quality(size)

        self.accept()


class VersionTable(QTableWidget):
    def __init__(self, idx, parent=None):
        super().__init__(parent)
        self.dialog = parent
        self.idx = idx
        self.setShowGrid(False)
        self.setSelectionMode(QAbstractItemView.SingleSelection)
        self.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.setAlternatingRowColors(True)
        self.horizontalHeader().setStretchLastSection(True)
        self.verticalHeader().hide()
        self.setColumnCount(3)
        self.setColumnWidth(0, 80)
        self.setColumnWidth(1, 80)
        labels = ['Width', 'Height', 'Bandwidth']
        self.setHorizontalHeaderLabels(labels)
        self.currentItemChanged.connect(self.on_selection_changed)

    def populate_table(self, data):
        row = self.rowCount()
        for datum in data:
            self.insertRow(row)
            self.setRowHeight(row, 20)
            width, height = datum["resolution"]
            item = QTableWidgetItem()
            item.setText(str(width))
            item.setTextAlignment(Qt.AlignRight)
            self.setItem(row, 0, item)
            item = QTableWidgetItem()
            item.setText(str(height))
            item.setTextAlignment(Qt.AlignRight)
            self.setItem(row, 1, item)
            #version = self.get_version(datum)
            item = QTableWidgetItem()
            item.setText("     %s" % str(datum["bandwidth"]))
            self.setItem(row, 2, item)
            row += 1

    def get_version(self, item):
        version = "   %s" % item["name"]
        lang = item["lang"]
        if lang is not None:
            version = version + " " + lang

        return version

    def set_selection(self, row):
        self.blockSignals(True)
        self.selectRow(row)
        QCoreApplication.processEvents()
        self.blockSignals(False)

    def on_selection_changed(self, new, old):
        if new is None:
            self.reverse_selection(old)
            return

        self.dialog.on_selection_changed(new.row())

    def reverse_selection(self, item):
        self.blockSignals(True)
        self.clearSelection()
        QCoreApplication.processEvents()
        self.setCurrentItem(item)
        self.blockSignals(False)

