#!/usr/bin/python
# -*- coding: utf-8 -*-

# Copyright (C) 2012 Huayra GNU/Linux
#
# Author Miguel Angel Garcia <miguelgarcia@anses.gov.ar>
#
# 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 2
# of the License
#
# 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 gtk
import webkit
import os
import urlparse
import subprocess


def set_hostname(new_hostname):
    code = os.system("pkexec /usr/sbin/huayra-identinet-set " + new_hostname)
    return code == 0


def get_hostname():
    return subprocess.check_output("hostname")


class IdentinetSetupView(webkit.WebView):
    """
    Widget for hostname setup.
    """
    def __init__(self, base_dir):
        webkit.WebView.__init__(self)
        self.get_property("settings").set_property(
            "enable-default-context-menu", False)
        self.base_url = "file:///" + base_dir
        self.base_dir = base_dir
        self.connect('navigation-policy-decision-requested',
            self._on_navigate_decision)
        self.show_page("identinet_setup.html")

    def show_page(self, page):
        content = open(self.base_dir + page, 'r').read()
        content = content.replace('{{ hostname }}', get_hostname())
        self.load_html_string(content, base_uri=self.base_url)

    def _on_navigate_decision(self, view, frame, req, action, decision):
        """
        Dispatchs actions from pages to program methods.
        """
        parts = req.get_uri().split("://", 1)
        if len(parts) == 2:
            if parts[0] == 'ui':
                params = parts[1].split("?", 1)
                if params[0] == 'set_hostname':
                    qs = urlparse.parse_qs(params[1])
                    hostname = qs['hostname'][0] if 'hostname' in qs else ''
                    if set_hostname(hostname):
                        self.show_page("identinet_setup.html")
                if params[0] == 'close':
                    gtk.main_quit()
                return True
        return False


def build_app_window(start_page):
    """
    Build application window.
    """
    sw = gtk.ScrolledWindow()
    identinet_view = IdentinetSetupView(start_page)
    sw.add(identinet_view)
    win = gtk.Window(gtk.WINDOW_TOPLEVEL)
    win.add(sw)
    win.set_resizable(False)
    identinet_view.set_size_request(600, 400)
    win.set_default_size(600, 400)
    win.set_title("Huayra Identinet")
    win.set_position(gtk.WIN_POS_CENTER)
    path = "/usr/share/icons/hicolor/scalable/apps/"
    win.set_icon_from_file(path + "huayra-identinet.svg")
    win.connect("destroy", gtk.main_quit)
    return win


if __name__ == '__main__':
    win = build_app_window(
        "/usr/share/huayra-identinet/pages/")
    win.show_all()
    gtk.main()
