# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright 2016 Continuum Analytics, Inc.
#
# May be copied and distributed freely only as part of an Anaconda or
# Miniconda installation.
# -----------------------------------------------------------------------------
"""Home Tab."""

from __future__ import absolute_import, division, print_function

# Standard library imports
import sys

# Third party imports
from qtpy.QtCore import Qt, Signal
from qtpy.QtGui import QPixmap
from qtpy.QtWidgets import QHBoxLayout, QLabel, QProgressBar, QVBoxLayout

# Local imports
from anaconda_navigator.api.anaconda_api import AnacondaAPI
from anaconda_navigator.static import images
from anaconda_navigator.utils.styles import load_style_sheet
from anaconda_navigator.widgets import (ButtonNormal, FrameTabContent,
                                        FrameTabFooter, FrameTabHeader,
                                        LabelBase, SpacerHorizontal,
                                        WidgetBase)
from anaconda_navigator.widgets.lists.apps import (ListItemApplication,
                                                   ListWidgetApplication)


# --- Custom widgets used with CSS styling
# -----------------------------------------------------------------------------
class ButtonHomeRefresh(ButtonNormal):
    """QFrame used for CSS styling refresh button inside the Home Tab."""


class LabelHome(LabelBase):
    """QLabel used for CSS styling the Home Tab label."""

    pass


# --- Main widget
# -----------------------------------------------------------------------------
class HomeTab(WidgetBase):
    """Home applications tab."""

    sig_pointer_updated = Signal(object, object)
    sig_status_updated = Signal(object, object, object, object)
    sig_application_updated = Signal(object, object)

    def __init__(self, parent=None):
        """Home applications tab."""
        super(HomeTab, self).__init__(parent)

        # Variables
        self._parent = parent
        self.api = AnacondaAPI()
        self.setObjectName('Tab')

        # Widgetsugh
        main_icon = QLabel()
        self.list_applications = ListWidgetApplication()
        self.apps = None
        self.app_timers = None
        self.button_refresh = ButtonHomeRefresh('Refresh')
        self.frame_home_top = FrameTabHeader(self)
        self.frame_home_body = FrameTabContent(self)
        self.frame_home_bottom = FrameTabFooter(self)
        self.label_home = LabelHome('')
        self.label_status_action = QLabel('')
        self.label_status = QLabel('')
        self.progress_bar = QProgressBar()

        # Widget setup
        self.progress_bar.setTextVisible(False)
        pixmap = QPixmap(images.ANACONDA_ICON_128_PATH)
        main_icon.setPixmap(pixmap)
        main_text = ('My Applications')
        self.label_home.setText(main_text)
        self.list_applications.setVerticalScrollBarPolicy(
            Qt.ScrollBarAlwaysOn)

        # Layout
        layout_top = QHBoxLayout()
        layout_top.addWidget(self.label_home, 10, Qt.AlignLeft)
        layout_top.addWidget(self.button_refresh, 1,
                             Qt.AlignRight | Qt.AlignBottom)
        self.frame_home_top.setLayout(layout_top)

        layout_body = QVBoxLayout()
        layout_body.addWidget(self.list_applications)
        self.frame_home_body.setLayout(layout_body)

        layout_bottom = QHBoxLayout()
        layout_bottom.addWidget(self.label_status_action)
        layout_bottom.addWidget(SpacerHorizontal())
        layout_bottom.addWidget(self.label_status)
        layout_bottom.addStretch()
        layout_bottom.addWidget(self.progress_bar)
        self.frame_home_bottom.setLayout(layout_bottom)

        layout = QVBoxLayout()
        layout.addWidget(self.frame_home_top)
        layout.addWidget(self.frame_home_body)
        layout.addWidget(self.frame_home_bottom)
        self.setLayout(layout)

        # Signals
        self.list_applications.sig_application_updated.connect(
            self.sig_application_updated)
        self.list_applications.sig_application_updated.connect(
            self.update_list)
        self.list_applications.sig_status_updated.connect(
            self.update_status)
        self.button_refresh.clicked.connect(self.refresh_cards)
        self.progress_bar.setVisible(False)

    def update_list(self, name=None, version=None):
        """Update applications list."""
        self.set_applications()
        self.label_status.setVisible(False)
        self.label_status_action.setVisible(False)
        self.progress_bar.setVisible(False)

    def refresh_cards(self):
        """Refresh application widgets.

        List widget items sometimes are hidden on resize. This method tries
        to compensate for that refreshing and repainting on user demand.
        """
        self.list_applications.update_style_sheet()
        self.list_applications.repaint()
        for item in self.list_applications.items():
            if not item.widget.isVisible():
                item.widget.repaint()

    def update_status(self, action, status, progress, max_value):
        """Update the application action status."""
        self.label_status_action.setText(action)
        self.label_status.setText(status)
        self.label_status.setVisible(True)
        self.label_status_action.setVisible(True)
        self.progress_bar.setVisible(True)
        self.progress_bar.setMaximum(max_value)
        self.progress_bar.setValue(progress)

        for item in self.list_applications._items:
            item.widget.setVisible(True)
            item.setHidden(False)
            item.widget.repaint()

    def setup_tab(self, apps):
        """Setup the tab content."""
        self.apps = apps
        self.set_applications()

    def set_applications(self):
        """Build the list of applications present in the current conda env."""
        all_applications = []
        installed_applications = []
        not_installed_applications = []

        prefix = self.api.ROOT_PREFIX
        for app_name in sorted(list(self.apps.keys())):
            app = self.apps[app_name]
            item = ListItemApplication(name=app['name'],
                                       description=app['description'],
                                       versions=app['versions'],
                                       command=app['command'],
                                       image_path=app['image_path'],
                                       prefix=prefix)
            if item.installed:
                installed_applications.append(item)
            else:
                not_installed_applications.append(item)

        all_applications = installed_applications + not_installed_applications

        self.list_applications.clear()
        self.list_applications.setUpdatesEnabled(False)
        for i in all_applications:
            self.list_applications.addItem(i)
            self.list_applications.update_style_sheet()
        self.list_applications.setUpdatesEnabled(True)

    def update_versions(self, apps=None):
        """Update applications versions."""
        self.items = []

        for i in range(self.list_applications.count()):
            item = self.list_applications.item(i)
            self.items.append(item)
            if isinstance(item, ListItemApplication):
                name = item.name
                meta = apps.get(name)
                if meta:
                    versions = meta['versions']
                    version = self.api.get_dev_tool_version(item.path)
                    item.update_versions(version, versions)

    def update_style_sheet(self, style_sheet=None):
        """Update custom CSS style sheet."""
        if style_sheet is None:
            style_sheet = load_style_sheet()
        self.list_applications.update_style_sheet(style_sheet=style_sheet)
        self.setStyleSheet(style_sheet)


# --- Local testing
# -----------------------------------------------------------------------------
def test():  # pragma: no cover
    """Run local test."""
    from anaconda_navigator.static.images import ANACONDA_ICON_256_PATH
    from anaconda_navigator.utils.qthelpers import qapplication

    app = qapplication()
    widget = HomeTab()
    apps = {}
    for i in range(6):
        name = "Package {0}".format(i)
        application = dict(
            name=name,
            description="Scientific PYthon Development EnviRonment",
            versions=[str(i), str(i), str(i + 1)],
            image_path=ANACONDA_ICON_256_PATH,
            command=None)
        apps[name] = application
    widget.setup_tab(apps)
    widget.update_style_sheet()
    widget.showMaximized()
    sys.exit(app.exec_())


if __name__ == "__main__":  # pragma: no cover
    test()
