# Copyright (C) 2011 Canonical
#
# Authors:
#  Michael Vogt
#
# 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; version 3.
#
# 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 Street, Fifth Floor, Boston, MA 02110-1301 USA

import logging
import subprocess

from gettext import gettext as _
from gi.repository import Gdk
from gi.repository import WebKit2

# FIXME: remove this try/except and add a dependency on gir1.2-gstreamer-0.10
#        if we (ever) start using VideoPlayerGtk3
try:
    from gi.repository import Gst
except ImportError:
    pass

from gi.repository import Gtk

from softwarecenter.ui.gtk3.widgets.webkit import SCWebKit

LOG = logging.getLogger(__name__)


class VideoPlayer(Gtk.VBox):
    def __init__(self):
        super(VideoPlayer, self).__init__()
        self.set_size_request(400, 255)
        self.webkit = SCWebKit()
        settings = self.webkit.get_settings()
        # this disables the flash and other plugins so that we force html5
        # video on the system. This is works currently (11/2011) fine with
        # dailymotion and vimeo but youtube is opt-in only so we need
        # to monitor the situation
        settings.set_property("enable-plugins", False)
        # on navigation/new window etc, just use the proper browser
        self.webkit.connect(
            "decide-policy", self._on_decide_policy)
        self.webkit.connect("create", self._on_create_web_view)
        self.pack_start(self.webkit, True, True, 0)
        self._uri = ""

    # helper required to follow ToS about the "back" link (flash version)
    def _on_decide_policy(self, decision, decision_type):
        if decision_type == WebKit2.PolicyDecisionType.NEW_WINDOW_ACTION:
            request = decision.get_request()
            subprocess.Popen(['xdg-open', request.uri])
            decision.ignore()
            return True

        return False

    # helper for the embedded html5 viewer
    def _on_create_web_view(self, view, action):
        # mvo: this is not ideal, the trouble is that we do not get the
        #      url that the new view points to until after the view was
        #      created. But we don't want to be a full blow internal
        #      webbrowser so we simply go back to the youtube url here
        #      and the user needs to click "youtube" there again :/
        req = action.get_request()
        subprocess.Popen(['xdg-open', req.uri])

    # uri property
    def _set_uri(self, v):
        self._uri = v or ""
        if self._uri:
            # only load the uri if it's defined, otherwise we may get:
            # Program received signal SIGSEGV, Segmentation fault.
            # webkit_web_frame_load_uri () from /usr/lib/libwebkitgtk-3.0.so.0
            self.webkit.uri = self._uri

    def _get_uri(self):
        return self._uri
    uri = property(_get_uri, _set_uri, None, "uri property")

    def load_html(self, html):
        """ Instead of a video URI use a html embedded video like e.g.
            youtube or vimeo. Note that on a default install not all
            video codecs will play (no flash!), so be careful!
        """
        # FIXME: add something more useful here
        base_uri = "http://www.ubuntu.com"
        self.webkit.load_html(html, base_uri)

    def stop(self):
        self.webkit.load_uri('')
