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

# mainui.py
# This file is part of qarte-5
#    
# Author: Vincent Vande Vyvre <vincent.vandevyvre@oqapy.eu>
# Copyright: 2011-2024 Vincent Vande Vyvre
# Licence: GPL3
# Home page: https://launchpad.net/qarte
#
# Main window

import sys
import os
import logging
lgg = logging.getLogger(__name__)

from PyQt5.QtCore import (Qt, QRect, QSize, QCoreApplication, pyqtSignal,
                          QMimeData, QPoint, QTimer, )
from PyQt5.QtGui import (QIcon, QPixmap, QDrag, QPainter, QPen, )
from PyQt5.QtWidgets import (QMainWindow, QWidget, QGridLayout, QSplitter,
                             QVBoxLayout, QHBoxLayout, QSizePolicy, QMenuBar,
                             QTableWidget, QPlainTextEdit, QMenu, QStatusBar,
                             QAction, QListWidget, QAbstractItemView, 
                             QListWidgetItem, QListView, QStackedWidget, 
                             QPlainTextEdit, QLabel, QPushButton, 
                             QProgressBar, QToolButton, QSpacerItem, 
                             QButtonGroup, QTableWidgetItem, QComboBox)

from .basket import Basket
from .uiconcerts import UiConcerts
from .VWidgets_qt5.vlineedit import VLineEdit
from .commonwidgets.horizontalslider import HorizontalSlider
from data import VERSION_STR


class MainUi(QMainWindow):
    def __init__(self, core, size):
        super().__init__()
        self.core = core
        self.resize(size[0], size[1])
        self.setWindowTitle("Qarte-%s" % VERSION_STR)
        appIcon = QIcon()
        appIcon.addPixmap(QPixmap("medias/qarte_logo.png"))
        self.setWindowIcon(appIcon)
        QCoreApplication.instance().setWindowIcon(appIcon)
        self.centralwidget = QWidget(self)
        self.gridLayout = QGridLayout(self.centralwidget)
        self.stackedWidget = QStackedWidget(self.centralwidget)
        self.plus_pg = QWidget()
        self.hl_1 = QVBoxLayout(self.plus_pg)
        self.hl_1.setContentsMargins(0, 0, 0, 0)
        self.splitter_2 = QSplitter(self.plus_pg)
        self.splitter_2.setOrientation(Qt.Horizontal)
        self.splitter = QSplitter(self.splitter_2)
        self.splitter.setOrientation(Qt.Vertical)
        self.views = QWidget(self.splitter)
        self.vl_15 = QVBoxLayout(self.views)
        self.arte_list = ArteTVVideoList(self, self.views)
        self.vl_15.addWidget(self.arte_list)
        self.widget = QWidget(self.splitter)
        self.vl_1 = QVBoxLayout(self.widget)
        self.vl_1.setContentsMargins(0, 0, 0, 0)
        # Sorting widgets
        self.widget1 = QWidget(self.widget)
        sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
                            self.widget1.sizePolicy().hasHeightForWidth())
        self.widget1.setSizePolicy(sizePolicy)
        self.hl_2 = QHBoxLayout(self.widget1)
        self.hl_2.setContentsMargins(6, 2, 6, 2)
        self.filter_lbl = QLabel(self.widget1)
        self.filter_lbl.setText('Filter: ')
        self.hl_2.addWidget(self.filter_lbl)
        self.filter_led = VLineEdit(self.widget1)
        self.filter_led.setMaximumSize(250, 32)
        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.hl_2.addWidget(self.filter_led)
        self.showall_btn = QToolButton(self.widget1)
        icon1 = QIcon()
        icon1.addPixmap(QPixmap("medias/refresh.png"))
        self.showall_btn.setIcon(icon1)
        self.showall_btn.setIconSize(QSize(20, 20))
        self.showall_btn.setEnabled(False)
        self.hl_2.addWidget(self.showall_btn)
        self.result_lbl = QLabel(self.widget1)
        self.hl_2.addWidget(self.result_lbl)
        self.categories_cmb = QComboBox(self)
        self.categories_cmb.setMinimumSize(200, 24)
        self.hl_2.addWidget(self.categories_cmb)
        self.refresh_btn = QToolButton(self.widget1)
        icon2 = QIcon()
        icon2.addPixmap(QPixmap("medias/refresh.png"))
        self.refresh_btn.setIcon(icon2)
        self.refresh_btn.setIconSize(QSize(20, 20))
        self.refresh_btn.setEnabled(False)
        self.hl_2.addWidget(self.refresh_btn)
        spacer = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.hl_2.addItem(spacer)
        self.sizer_wdg = HorizontalSlider(self.widget1)
        self.sizer_wdg.set_range((100, 200))
        self.sizer_wdg.set_value(self.core.cfg.get('thumb1'))
        self.sizer_wdg.setMaximumSize(200, 32)
        icon2 = QIcon()
        icon2.addPixmap(QPixmap("medias/minus_white_20x5.png"))
        self.sizer_wdg.minus.setIcon(icon2)
        icon3 = QIcon()
        icon3.addPixmap(QPixmap("medias/plus_white_20x20.png"))
        self.sizer_wdg.plus.setIcon(icon3)
        self.hl_2.addWidget(self.sizer_wdg)

        self.vl_1.addWidget(self.widget1)
        self.pitch_editor = QPlainTextEdit(self.widget)
        self.pitch_editor.setReadOnly(True)
        self.vl_1.addWidget(self.pitch_editor)
        self.basket1_area = QWidget(self.splitter_2)
        self.vl_2 = QVBoxLayout(self.basket1_area)
        self.vl_2.setContentsMargins(0, 0, 0, 0)
        self.tv_basket = Basket(self, "TV", self.basket1_area)
        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
                    self.tv_basket.sizePolicy().hasHeightForWidth())
        self.tv_basket.setSizePolicy(sizePolicy)
        self.vl_2.addWidget(self.tv_basket)
        self.tv_basket_buttons = DownloadingWidgets(self, self.basket1_area)
        self.vl_2.addWidget(self.tv_basket_buttons)

        self.hl_1.addWidget(self.splitter_2)
        self.stackedWidget.addWidget(self.plus_pg)

        # arte concert page
        self.live_pg = UiConcerts(self)
        self.stackedWidget.addWidget(self.live_pg)
        self.gridLayout.addWidget(self.stackedWidget, 0, 0, 1, 1)
        self.setCentralWidget(self.centralwidget)
        self.menubar = QMenuBar(self)
        self.menubar.setGeometry(QRect(0, 0, 800, 24))
        self.menuQarte = QMenu(self.menubar)
        self.menuQarte.setObjectName("menuQarte")
        self.menuArte_TV = QMenu(self.menubar)
        self.menuArte_TV.setObjectName("menuArte_TV")
        self.menuArte_Concerts = QMenu(self.menubar)
        self.menuArte_Concerts.setObjectName("menuArte_Concerts")
        self.actionOptions = QAction(self)
        self.actionOptions.setObjectName("actionOptions")
        #self.actionD_iffered_download = QAction(self)
        #self.actionD_iffered_download.setObjectName("actionD_iffered_download")
        self.action_About = QAction(self)
        self.action_About.setObjectName("action_About")
        self.actionQ_uit = QAction(self)
        self.actionQ_uit.setObjectName("actionQ_uit")
        self.action_Reload = QAction(self)
        self.action_Reload.setObjectName("action_Reload")
        self.action_Download = QAction(self)
        self.action_Download.setObjectName("action_Download")
        self.action_Cancel = QAction(self)
        self.action_Cancel.setObjectName("action_Cancel")
        self.actionDo_wnload = QAction(self)
        self.actionDo_wnload.setObjectName("actionDo_wnload")
        self.actionCa_ncel = QAction(self)
        self.actionCa_ncel.setObjectName("actionCa_ncel")
        self.menuQarte.addAction(self.actionOptions)
        #self.menuQarte.addAction(self.actionD_iffered_download)
        self.menuQarte.addAction(self.action_About)
        self.menuQarte.addAction(self.actionQ_uit)
        self.menuArte_TV.addAction(self.action_Reload)
        self.menuArte_TV.addAction(self.action_Download)
        self.menuArte_TV.addAction(self.action_Cancel)
        self.menuArte_Concerts.addAction(self.actionDo_wnload)
        self.menuArte_Concerts.addAction(self.actionCa_ncel)
        self.menubar.addAction(self.menuQarte.menuAction())
        self.menubar.addAction(self.menuArte_TV.menuAction())
        self.menubar.addAction(self.menuArte_Concerts.menuAction())
        self.setMenuBar(self.menubar)
        self.action_Download.setEnabled(False)
        self.action_Cancel.setEnabled(False)
        self.actionDo_wnload.setEnabled(False)
        self.actionCa_ncel.setEnabled(False)

        self.statusbar = QStatusBar(self)
        self.statusbar.setObjectName("statusbar")

        self.form_button = QWidget()
        self.form_button.setMinimumSize(QSize(200, 20))
        self.form_button.setMaximumSize(QSize(200, 20))
        self.grid_button = QGridLayout(self.form_button)
        self.grid_button.setContentsMargins(0, 0, 0, 0)
        self.grid_button.setSpacing(0)

        self.group = QButtonGroup(self.form_button)
        self.plus_state_btn = QPushButton()
        self.plus_state_btn.setMaximumSize(100, 24)
        self.plus_state_btn.setText("arte TV")
        self.plus_state_btn.setCheckable(True)
        self.plus_state_btn.setChecked(True)
        self.group.addButton(self.plus_state_btn)
        self.grid_button.addWidget(self.plus_state_btn, 0, 0, 1, 1)
        self.live_state_btn = QPushButton()
        self.live_state_btn.setMaximumSize(100, 24)
        self.live_state_btn.setText("arte Concert")
        self.live_state_btn.setCheckable(True)
        self.group.addButton(self.live_state_btn)
        self.grid_button.addWidget(self.live_state_btn, 0, 1, 1, 1)
        self.statusbar.addPermanentWidget(self.form_button)
        self.setStatusBar(self.statusbar)

        if self.core.cfg.get('filter_keys'):
            self.filter_led.add_historic_entries(self.core.cfg.get('filter_keys'))

        self.stackedWidget.setCurrentIndex(0)

        self.retranslateUi()

    def resize_splitters(self):
        h, h1 = self.splitter.sizes()[0], self.splitter.sizes()[1]
        r = int((h + h1) / 5)
        self.splitter.setSizes([r * 4, r])
        h, h1 = self.splitter_2.sizes()[0], self.splitter_2.sizes()[1]
        r = (h + h1) - 300
        self.splitter_2.setSizes([r, 300])

    def keyPressEvent(self, event):
        if event.key() == Qt.Key_Space:
            if self.core.artelive.on_space_key_pressed():
                event.accept()

            else:
                event.ignore()

    def configure_signals(self):
        buttons = self.tv_basket_buttons
        buttons.dwnld_btn.clicked.connect(self.core.artetv.start_download)
        buttons.cancel_btn.clicked.connect(self.core.artetv.cancel_download)
        self.filter_led.commandTriggered.connect(self.core.artetv.set_filter)
        self.filter_led.editingFinished.connect(self.core.artetv.set_filter)
        self.showall_btn.clicked.connect(self.core.artetv.remove_filter)
        self.sizer_wdg.valueChanged.connect(self.core.artetv.resize_thumbnails)
        self.actionOptions.triggered.connect(self.core.display_config_dialog)
        #self.actionD_iffered_download.triggered.connect(
                                        #self.core.create_deferred_task)
        self.action_About.triggered.connect(self.core.display_about_dialog)
        self.actionQ_uit.triggered.connect(self.closeEvent)
        self.action_Reload.triggered.connect(self.core.reload_arte_tv)
        self.action_Download.triggered.connect(self.core.artetv.start_download)
        self.action_Cancel.triggered.connect(self.core.artetv.cancel_download)
        self.actionDo_wnload.triggered.connect(self.core.artelive.start_download)
        self.actionCa_ncel.triggered.connect(self.core.artelive.cancel_download)
        self.plus_state_btn.clicked.connect(self.show_plus_page)
        self.live_state_btn.clicked.connect(self.show_live_page)
        #self.live_pg.file_name_led.editingFinished.connect(
                                            #self.core.artelive.edit_file_name)
        buttons = self.live_pg.dl_live_wdg
        buttons.dwnld_btn.clicked.connect(self.core.artelive.start_download)
        buttons.cancel_btn.clicked.connect(self.core.artelive.cancel_download)

    def set_categories_items(self, items):
        for i in items:
            self.categories_cmb.addItem(i[0])

    def show_plus_page(self):
        self.stackedWidget.setCurrentIndex(0)
        #self.actionD_iffered_download.setEnabled(True)

    def show_live_page(self):
        self.stackedWidget.setCurrentIndex(1)
        QCoreApplication.processEvents()
        self.live_pg.resize_splitter()
        #self.actionD_iffered_download.setEnabled(False)

    def closeEvent(self, event):
        if self.core.close_application():
            QCoreApplication.processEvents()
            import gc
            gc.collect()
            sys.exit()
        else:
            event.ignore()

    def retranslateUi(self):
        self.setWindowTitle(_("Qarte-%s" % VERSION_STR))
        self.menuQarte.setTitle(_("&Qarte"))
        self.menuArte_TV.setTitle(_("arte &TV"))
        self.menuArte_Concerts.setTitle(_("a&rte Concerts"))
        self.actionOptions.setText(_("&Options"))
        #self.actionD_iffered_download.setText(_("D&eferred download"))
        self.action_About.setText(_("&About"))
        self.actionQ_uit.setText(_("Q&uit"))
        self.action_Reload.setText(_("&Reload"))
        self.action_Download.setText(_("&Download"))
        self.action_Cancel.setText(_("&Cancel"))
        self.actionDo_wnload.setText(_("Do&wnload"))
        self.actionCa_ncel.setText(_("Ca&ncel"))

class ArteTVVideoList(QListWidget):
    itemDragged = pyqtSignal(int)
    def __init__(self, ui, parent=None):
        super().__init__(parent)
        self.ui = ui
        self.core = ui.core
        self.video_items = []
        self.is_complete = False
        self.setDragEnabled(True)
        self.setDragDropMode(QAbstractItemView.DragDrop)
        self.setDefaultDropAction(Qt.MoveAction)
        self.setSelectionMode(QAbstractItemView.SingleSelection)
        s = self.core.cfg.get('thumb1')
        self.setIconSize(QSize(s, s))
        self.setFlow(QListView.LeftToRight)
        self.setViewMode(QListView.IconMode)
        self.itemSelectionChanged.connect(self.selection_changed)

    def display_videos(self, videos=None):
        if videos is None:
            videos = self.core.artetv.videos
        self.clear()
        #self.video_items = []
        self.is_complete = False
        for idx, video in enumerate(videos):
            item = PreviewTVItem(self.ui, video, idx)
            self.addItem(item)
            # Needed ?
            #self.video_items.append(item)
        self.is_complete = True
        QCoreApplication.processEvents()

    def display_filtered_videos(self, videos):
        self.clear()
        #self.video_items = []
        self.is_complete = False
        for idx, video in videos:
            item = PreviewTVItem(self.ui, video, idx)
            self.addItem(item)
            # Needed ?
            #self.video_items.append(item)
        self.is_complete = True
        QCoreApplication.processEvents()

    def display_category(self, videos):
        lgg.info("Display %s items" % len(videos))
        self.clear()
        self.video_items = []
        self.is_complete = False
        for idx, video in enumerate(videos):
            item = PreviewTVItem(self.ui, video, idx)
            self.addItem(item)
            self.video_items.append(item)
        self.core.artetv.is_in_category = True
        self.is_complete = True
        QCoreApplication.processEvents()

    def startDrag(self, event):
        it = self.itemAt(event.pos())
        if not it:
            return

        if it.item.idx.startswith("RC"):
            return

        idx = it.index
        mimeData = QMimeData()
        mimeData.setText('new %s' % str(idx))
        drag = QDrag(self)
        drag.setMimeData(mimeData)
        pixmap = it.icon().pixmap(QSize(180, 102))
        drag.setPixmap(pixmap)
        drag.setHotSpot(QPoint(90, 102))
        #drag.setPixmap(pixmap)
        result = drag.exec_(Qt.MoveAction)
        self.itemDragged.emit(idx)

    def mouseMoveEvent(self, event):
        self.startDrag(event)
        event.accept()

    def mousePressEvent(self, event):
        item = self.itemAt(event.pos())
        if not item:
            self.clearSelection()
            event.accept()

        elif event.button() == 1:
            item.setSelected(True)
            self.core.on_tv_item_selected(item.index)
            event.accept()

        else:
            event.ignore()

    def contextMenuEvent(self, event):
        item = self.itemAt(event.pos())
        if item is not None:
            item.show_context_menu(event.globalPos())
        event.accept()

    def mouseDoubleClickEvent(self, event):
        if self.itemAt(event.pos()):
            self.move_item(self.itemAt(event.pos()))
            event.accept()
        else:
            event.ignore()

    def resizeEvent(self, event):
        if self.is_complete:
            s = self.spacing()
            self.setSpacing(s)
            self.updateGeometries()
            w, h = self.ui.size().width(), self.ui.size().height()
            self.core.cfg.update("size", (w, h))
            event.ignore()

    def set_scrolling_value2(self):
        self.verticalScrollBar().setRange(0, self.viewport().height())
        self.verticalScrollBar().setPageStep(self.viewport().height()/8)

    def selection_changed(self):
        item = self.selectedItems()
        if item:
            self.core.artetv.edit_summary(item[0].item)

    def move_item(self, item):
        """Item in preview windows has double-clicked.

        When an item in preview has double-clicked, he's moved to
        download basket.

        Args:
        item -- item double-clicked
        """
        self.ui.tv_basket.add_object(item.index)

class PreviewTVItem(QListWidgetItem):
    def __init__(self, ui, item, idx, parent=None):
        super().__init__(parent)
        self.ui = ui
        self.arte = ui.core.artetv
        self.item = item
        self.index = idx
        self.is_double_clicked = False
        img = self.draw_image(item.pixmap)
        self.setIcon(QIcon(img))
        text = self.set_thumbnail_text(item.title)
        self.setText(text)
        self.setTextAlignment(Qt.AlignHCenter)
        self.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)

    def draw_image(self, path):
        """Create the thumbnails for preview.

        Thumbnails are painted on a background wich content the shadow and
        a white frame is painted around the image.

        Args:
        path -- image path

        Returns:
        thumbnail
        """
        #lgg.info("Draw item icon: %s" % path)
        back = QPixmap("medias/shadow.png")
        img = QPixmap(path).scaled(QSize(180, 102),
                                   Qt.KeepAspectRatio, 
                                   Qt.SmoothTransformation)
        if img.isNull():
            img = QPixmap("medias/noPreview.png").scaled(QSize(180, 102))

        w = QSize.width(img.size())
        h = QSize.height(img.size())
        # white frame
        brect = QRect(0, 0, w+3, h+3)
        bckgrnd = back.scaled(QSize(w+25, h+25))
        painter = QPainter()
        painter.begin(bckgrnd)
        painter.setPen(QPen(Qt.white, 1, Qt.SolidLine, Qt.RoundCap,
                            Qt.MiterJoin))
        painter.drawRect(brect)
        rect = QRect(2, 2, w, h)
        # painting source
        irect = QRect(0, 0, w, h)
        painter.drawPixmap(rect, img, irect)
        painter.end()

        return bckgrnd

    def set_thumbnail_text(self, txt):
        """Format the movie's title.

        Args:
        txt -- title

        Returns:
        Formated text
        """
        if len(txt) < 21:
            return txt

        form = ""
        while 1:
            chain = txt[:21]
            count = len(chain) - 1
            while 1:
                if chain[count] == " ":
                    break

                count -= 1
                if count == 0:
                    count = len(chain) - 1
                    break

            form = form + chain[:count] + "\n"
            txt = txt[count+1:]
            if not txt:
                break

            elif len(txt) < 21:
                form = form + txt + "\n"
                break

        return form[:-1]

    def show_context_menu(self, pos):
        self._show_menu(pos)

    def _show_menu(self, pos):
        """Build and show context menu.

        Keyword arguments:
        pos -- event.pos()
        """
        self.menu = QMenu()
        self.act_add = QAction(self.menu)
        self.act_add.setText(_("Add to download list"))
        self.menu.addAction(self.act_add)
        self.act_show = QAction(self.menu)
        self.act_show.setText(_("Show summary"))
        self.menu.addAction(self.act_show)
        #self.act_def = QAction(self.menu)
        #self.act_def.setText(_("Deferred download"))
        #self.menu.addAction(self.act_def)
        self.act_add.triggered.connect(self.add_to_download)
        self.act_show.triggered.connect(self.show_pitch)
        #self.act_def.triggered.connect(self.set_cron_job)
        self.menu.popup(pos)

    def add_to_download(self):
        """Append video to download basket.

        """
        self.ui.tv_basket.add_object(self.index)

    def show_pitch(self):
        """Show the summary.

        """
        self.arte.edit_summary(self.item)

    def set_cron_job(self):
        """Set a deferred download.

        """
        self.arte.download_later(self.item)

class DownloadingWidgets(QWidget):
    """Define the dowloading widgets; buttons, progressBar, labels.

    """
    def __init__(self, ui, parent=None):
        super().__init__(parent)
        self.setMaximumSize(QSize(300, 16777215))
        self.ui = ui
        self.vl_13 = QVBoxLayout(self)
        self.vl_13.setContentsMargins(2, 0, 2, 2)
        self.vl_13.setSpacing(2)
        self.hl_13 = QHBoxLayout()
        self.hl_13.setSpacing(0)
        self.dwnld_btn = QPushButton(self)
        self.dwnld_btn.setMinimumSize(QSize(50, 40))
        self.dwnld_btn.setMaximumSize(QSize(50, 40))
        self.dwnld_btn.setStyleSheet("QPushButton:hover" 
                                            "{border: 2px solid #9900FF;}")
        icon4 = QIcon()
        icon4.addPixmap(QPixmap("medias/download_44x30.png"), 
                                QIcon.Normal, QIcon.Off)
        self.dwnld_btn.setIcon(icon4)
        self.dwnld_btn.setIconSize(QSize(44, 30))
        self.dwnld_btn.setFlat(True)
        self.dwnld_btn.setEnabled(False)
        self.dwnld_btn.setObjectName("dwnld_btn")
        self.hl_13.addWidget(self.dwnld_btn)
        self.progressBar = QProgressBar(self)
        self.progressBar.setProperty("value", 0)
        self.progressBar.setMinimumSize(QSize(100, 32))
        self.progressBar.setObjectName("progressBar")
        self.hl_13.addWidget(self.progressBar)
        self.cancel_btn = QPushButton(self)
        self.cancel_btn.setMinimumSize(QSize(50, 40))
        self.cancel_btn.setMaximumSize(QSize(50, 40))
        self.cancel_btn.setStyleSheet("""QPushButton:hover 
                                            {border: 2px solid #9900FF;}""")
        icon5 = QIcon()
        icon5.addPixmap(QPixmap("medias/stop_44x30.png"), 
                                QIcon.Normal, QIcon.Off)
        self.cancel_btn.setIcon(icon5)
        self.cancel_btn.setIconSize(QSize(44, 30))
        self.cancel_btn.setShortcut("Ctrl+S")
        self.cancel_btn.setFlat(True)
        self.cancel_btn.setEnabled(False)
        self.cancel_btn.setObjectName("cancel_btn")
        self.hl_13.addWidget(self.cancel_btn)
        self.vl_13.addLayout(self.hl_13)
        self.progress_lbl = QLabel(self)
        self.progress_lbl.setAlignment(Qt.AlignCenter)
        self.progress_lbl.setText("")
        self.progress_lbl.setObjectName("progress_lbl")
        self.vl_13.addWidget(self.progress_lbl)
        self.progress_lbl2 = QLabel(self)
        self.progress_lbl2.setAlignment(Qt.AlignCenter)
        self.progress_lbl2.setText("")
        self.progress_lbl2.setObjectName("progress_lbl2")
        self.vl_13.addWidget(self.progress_lbl2)

    def clear(self, all_=False):
        self.progressBar.setValue(0)
        self.cancel_btn.setEnabled(False)
        self.progress_lbl.setText("")
        self.progress_lbl2.setText("")
        if all_:
            self.dwnld_btn.setEnabled(False)

    def on_progress(self):
        self.dwnld_btn.setEnabled(False)
        self.cancel_btn.setEnabled(True)

    def set_merging_message(self, state):
        self.clear()
        if state:
            self.progress_lbl.setText("Merging audio-video ...")
            self.progressBar.setRange(0, 0)
            QCoreApplication.processEvents()

        else:
            self.progressBar.setRange(0, 100)
            self.progressBar.setValue(0)


class CategoryButton(QPushButton):
    triggered  = pyqtSignal(str)
    def __init__(self, idx, ui, parent=None):
        super(CategoryButton, self).__init__(parent)
        self.idx = idx
        self.ic_off = QIcon()
        self.ic_on = QIcon()
        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(60, 30))
        self.setFlat(True)
        self.setCheckable(True)
        self.clicked.connect(self.on_clicked)

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

    def set_icons(self, off, on):
        self.ic_off.addPixmap(QPixmap(off), 
                                QIcon.Normal, QIcon.Off)
        self.setIcon(self.ic_off)
        self.setIconSize(QSize(62, 37))
        self.ic_on.addPixmap(QPixmap(on), 
                                QIcon.Normal, QIcon.Off)

    def set_current(self, b):
        if b:
            self.setIcon(self.ic_on)
            self.is_current = True

        else:
            self.setIcon(self.ic_off)
            self.is_current = False

    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 on_clicked(self):
        if not self.is_current:
            self.triggered.emit(self.category)

    def update_icon(self):
        if self.is_current:
            self.setIcon(self.ic_off)
            self.is_current = False
        else:
            self.setIcon(self.ic_on)
            self.is_current = True

