#!/usr/bin/python3
# -*- coding:utf-8 -*-
#
# Copyright © 2012-2013 "Korora Project" <dev@kororaproject.org>
# Copyright © 2013-2015 "Manjaro Linux" <support@manjaro.org>
# Copyright © 2014-2022 "Jerry Bezencon" <valtam@linuxliteos.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the temms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 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, see <http://www.gnu.org/licenses/>.
#

import inspect
import os
import gi
from signal import signal, SIGINT, SIG_DFL
from subprocess import Popen
from sys import exit
try:
    # python 3
    from urllib.request import urlopen, pathname2url
except ImportError:
    # python 2
    from urllib import urlopen, pathname2url
from webbrowser import open_new_tab
from json import dumps as to_json
gi.require_version('WebKit2', '4.0')
gi.require_version('Gtk', '3.0')
from gi.repository import WebKit2 as WebKit
from gi.repository import Gtk
from gi.repository import GObject

class WelcomeConfig(object):
    def __init__(self):
        # store our base architecture
        if os.uname()[4] == 'x86_64':
            self._arch = '64-bit'
        else:
            self._arch = '32-bit'

        # store we are a live CD session
        self._live = os.path.exists('/bootmnt/manjaro')

        # store full path to our binary
        self._welcome_bin_path = os.path.abspath(inspect.getfile(inspect.currentframe()))

        # store directory to our welcome configuration
        self._config_dir = os.path.expanduser('~/.config/lite/welcome/')

        # store full path to our autostart symlink
        self._autostart_path = os.path.expanduser('~/.config/autostart/lite-welcome.desktop')

        # ensure our config directory exists
        if not os.path.exists(self._config_dir):
            try:
                os.makedirs(self._config_dir)
            except OSError as e:
                print(e)
                pass

        # does autostart symlink exist
        self._autostart = os.path.exists(self._autostart_path)

    def change_autostart(self, state):
        if state and not os.path.exists(self._autostart_path):
            # create the autostart symlink
            try:
                os.symlink('/usr/share/applications/lite-welcome.desktop', self._autostart_path )
            except OSError as e:
                print(e)
                pass
        elif not state and os.path.exists(self._autostart_path):
            # remove the autostart symlink
            try:
                os.unlink(self._autostart_path)
            except OSError as e:
                print(e)
                pass
        # determine autostart state based on absence of the disable file
        self._autostart = os.path.exists(self._autostart_path)

class LiteAppView(WebKit.WebView):
    def __init__(self):
        WebKit.WebView.__init__(self)

        self._config = WelcomeConfig()
        self.connect('load_changed', self._load_finished_cb)
        self.connect('decide-policy', self._nav_request_policy_decision_cb)
        self.l_uri = None

    def _push_config(self):
        # TODO: push notification should be connected to angularjs and use a broadcast event
        # any suitable controllers will be able to listen and respond accordingly, for now
        # we just use jQuery to manually toggle

        self.run_javascript("$('#arch').html('{}')".format(self._config._arch))
        self.run_javascript("$('#autostart').toggleClass('icon-check', {})\
            .toggleClass('icon-check-empty', {})".format(to_json
                (self._config._autostart), to_json(not self._config._autostart)))

        """self.execute_script("$('#{}').hide()".format(
            'buildmanjaro' if self._config._live else 'install'))
        self.execute_script("$('#{}').hide()".format(
            'donations' if self._config._live else 'install-cli'))
        self.execute_script("$('#{}').hide()".format(
            'password' if not self._config._live else '#'))
        """
    def _load_finished_cb(self, webview, event):
        if event == WebKit.LoadEvent.FINISHED:
            self._push_config()

    def _nav_request_policy_decision_cb(self, webview, decision, decision_type):
        if decision_type == WebKit.PolicyDecisionType.NAVIGATION_ACTION:
            action = decision.get_navigation_action()
            action_type = action.get_navigation_type()
            if action_type == WebKit.NavigationType.LINK_CLICKED:
                decision.ignore()
                uri = action.get_request().get_uri()
                #try:
                #    if uri.index('#') > 0:
                #        uri = uri[:uri.index('#')]
                #except ValueError:
                #    pass
                if uri.startswith('cmd://'):
                    self._do_command(uri)
                    return True
                if uri != '':
                    self.l_uri = uri
                    page = urlopen(uri)
                    self.load_html(page.read().decode("utf-8"), uri)
        else:
            if decision is not None:
                decision.use()


    def _do_command(self, uri):
        
        if uri.startswith('cmd://'):
            uri = uri[6:]
        if uri == 'start_updates':
            if os.path.exists("/usr/bin/lite-updates"):
                Popen(['pkexec', '/usr/bin/lite-updates'])
            else:
                      print('lite-software not installed'.format(uri))

        elif uri == 'install_drivers':
            if os.path.exists("/usr/bin/software-properties-gtk"):
                Popen(['/usr/bin/software-properties-gtk', '--open-tab=4'])
            else:
                      print('software-properties-gtk not installed'.format(uri))

        elif uri == 'timeshift':
            if os.path.exists("/usr/bin/timeshift-launcher"):
                Popen(['/usr/bin/timeshift-launcher'])
            else:
                      print('timeshift not installed'.format(uri))

        elif uri == 'start_software':
            if os.path.exists("/usr/bin/lite-software"):
                Popen(['pkexec', 'lite-software'])
            else:
                      print('lite-software not installed'.format(uri))

        elif uri == 'upgrade':
            if os.path.exists("/usr/bin/lite-upgrade-series6"):
                Popen(['/usr/bin/lite-upgrade-series6'])
            else:
                      print('lite-upgrade-series6 not installed'.format(uri))

        elif uri == 'lite-manual':
            Popen(['exo-open', "/usr/share/doc/litemanual/index.html"])

        elif uri == 'timeshf':
            Popen(['exo-open', "file:///usr/share/doc/litemanual/tutorials.html#timeshiftcreate"])

        elif uri == 'installlang':
            Popen(['exo-open', "file:///usr/share/doc/litemanual/install.html#setlang"])
            Popen(['/usr/bin/gnome-language-selector'])

        elif uri == 'lighttheme':
                Popen(["xfconf-query", "-c", "xsettings", "-p", "/Net/ThemeName", "-s", "Materia"])
                Popen(["xfconf-query", "-c", "xsettings", "-p", "/Net/IconThemeName", "-s", "Papirus-Adapta"])
                Popen(["zenity", "--title=Lite Welcome", "--info", "--width=320", "--text=Light Theme applied"])

        elif uri == 'darktheme':
                Popen(["xfconf-query", "-c", "xsettings", "-p", "/Net/ThemeName", "-s", "Materia-dark"])
                Popen(["xfconf-query", "-c", "xsettings", "-p", "/Net/IconThemeName", "-s", "Papirus-Adapta-Nokto"])
                Popen(["zenity", "--title=Lite Welcome", "--info", "--width=320", "--text=Dark Theme applied"])

        elif uri == 'roadmap':
            Popen(['exo-open', "https://www.linuxliteos.com/download.php#roadmap"])

        elif uri == 'hardware_database':
            Popen(['exo-open', 'https://www.linuxliteos.com/hardware.php'])

        elif uri == 'close':
            Gtk.main_quit()

        elif uri == 'toggle-startup':
            # toggle autostart
            check_uncheck = True if not self._config._autostart else False
            self._config.change_autostart(check_uncheck)

            self._push_config()

        elif uri.startswith("link?"):
            open_new_tab(uri[5:])

        else:
            print('Unknown command: {}'.format(uri))

        """Test env

class WelcomeApp(object):
    def __init__(self):
        # establish our location
        self._location = os.path.dirname(os.path.abspath(inspect.getfile(
            inspect.currentframe())))

        # check for relative path
        if os.path.exists(os.path.join(self._location, 'data/')):
            print('Using relative path for data source. Non-production testing.')
            self._data_path = os.path.join(self._location, 'data/')
        elif os.path.exists('/home/jerry/repo/git/litewelcome/usr/share/litewelcome/'):
            print('Using /home/jerry/repo/git/litewelcome/usr/share/litewelcome/ path.')
            self._data_path = '/home/jerry/repo/git/litewelcome/usr/share/litewelcome/'
        else:
            print('Unable to source the litewelcome data directory.')
            exit(1)

        """

class WelcomeApp(object):
    def __init__(self):
        # establish our location
        self._location = os.path.dirname(os.path.abspath(inspect.getfile(
            inspect.currentframe())))

        # check for relative path
        if os.path.exists(os.path.join(self._location, 'data/')):
            print('Using relative path for data source. Non-production testing.')
            self._data_path = os.path.join(self._location, 'data/')
        elif os.path.exists('/usr/share/litewelcome/'):
            print('Using /usr/share/litewelcome/path.')
            self._data_path = '/usr/share/litewelcome/'
        else:
            print('Unable to source the litewelcome data directory.')
            exit(1)

        self._build_app()

    def _build_app(self):
        # build window
        w = Gtk.Window()
        w.set_position(Gtk.WindowPosition.CENTER)

        # Active title/task bar
        w.set_title('Lite Welcome')

        # Initial window size
        w.set_size_request(768, 580)
        w.set_icon_from_file(os.path.join(self._data_path, "/usr/share/icons/Papirus/24x24/apps/litewelcome.png"))

        # build webkit container
        mv = LiteAppView()

        # load our index file
        file_out = os.path.abspath(os.path.join(self._data_path, 'index.html'))

        uri = 'file://' + pathname2url(file_out)
        mv.load_uri(uri)

        # build scrolled window widget and add our appview container
        sw = Gtk.ScrolledWindow()
        sw.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC)
        sw.add(mv)

        # build a an autoexpanding box and add our scrolled window
        b = Gtk.VBox(homogeneous=False, spacing=0)
        b.pack_start(sw, expand=True, fill=True, padding=0)

        # add the box to the parent window and show
        w.add(b)
        w.connect('delete-event', self.close)
        w.show_all()

        self._window = w
        self._appView = mv

    def run(self):
        signal(SIGINT, SIG_DFL)
        Gtk.main()

    def close(self, p1, p2):
        Gtk.main_quit(p1, p2)

app = WelcomeApp()
app.run()
