# Copyright (C) 2009 Canonical Ltd
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA

from PyQt4 import QtCore, QtGui


class HtmlReportView(object):
    """A generic location view displaying a html report."""

    def __init__(self, model, action_callback):
        self._model = model
        self._action_callback = action_callback
        self._view = self._build_view()

    def _build_view(self):
        """Return the constructed UI.

        :return: a QWidget.
        """
        browser = QtGui.QTextBrowser()
        browser.setOpenLinks(False)
        browser.connect(browser, QtCore.SIGNAL("anchorClicked(QUrl)"),
            self.do_link_action)
        return browser

    def do_link_action(self, href):
        action_str = unicode(href.toString())
        sep = action_str.find(' ')
        if sep == -1:
            command = action_str
            item = None
        else:
            command = action_str[:sep]
            item = action_str[sep + 1:]
        self._action_callback(command, item)

    def ui(self):
        self.refresh_view()
        return self._view

    def refresh_view(self):
        # TODO: process events as we append each 10 lines or so
        lines = self.report_text()
        self._view.clear()
        for i in lines:
            self._view.append(i)
        self._view.moveCursor(QtGui.QTextCursor.Start)

    def report_text(self):
        """Subclasses should implement this.

        :return: the HTML text to display.
        """
        raise NotImplementedError(self.report_text)
