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

# helpman - Manuals / Guides / Tutorials
# Copyright (C) 2017 Nathan SR <cquickcal@gmail.com> 

# License: 

#    helpman 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 3 of the License, or 
#    (at your option) any later version. 
# 
#    helpman 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 helpman.  If not, see <http://www.gnu.org/licenses/>. 

# Necessary Imports

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk 
from gi.repository import Gdk
from gi.repository import Pango
import subprocess
import re
import os, errno
import datetime
import time
import sys


# Following executes os commands passed on to it

def execute_command_I(full_command):
    proc = subprocess.Popen(full_command,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True,universal_newlines=True)
    (out, err) = proc.communicate()
    if err:
        result.set_text(err)
    else:
        select_manual_cbtext_III.remove_all()
        try:
            import StringIO
            # from StringIO import StringIO
            s = StringIO.StringIO(out)
        except ImportError:
            import io
            from io import StringIO
            s = io.StringIO(out)
        for line in s:
            select_manual_cbtext_III.append_text(line.strip())


def execute_command_II(full_command):
    proc = subprocess.Popen(full_command,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True,universal_newlines=True)
    (out, err) = proc.communicate()
    # if err:
    # result.set_text(err)
    # else:
    if out:
        textbuffer.set_text(out)
        result.set_text("")
        textview.grab_focus()
        start = textbuffer.get_start_iter()
        end = textbuffer.get_end_iter()
        textbuffer.place_cursor(start)
    else:
        textbuffer.set_text("")
        if smentry.get_text():
            result.set_text("No manual entry for " + smentry.get_text())    
        else:
            result.set_text("")

class Handler: 

# Helpman comboboxtext and their respective changed actions. Calls the functions above with their respective parameters.

    def manual_type_cbtext_1_changed(self, comboboxtext):
        result.set_text("")
        smentry.set_text("")
        textbuffer.set_text("")
        starting_with_cbtext_II.set_active(-1)
        select_manual_cbtext_III.remove_all()

    def starting_with_cbtext_2_changed(self, comboboxtext): 
        result.set_text("")
        smentry.set_text("")
        textbuffer.set_text("")
        select_manual_cbtext_III.remove_all()
        if manual_type_cbtext_I.get_active_text() and starting_with_cbtext_II.get_active_text():
            if starting_with_cbtext_II.get_active_text() == 'others':
                dynamic_command = "(LC_COLLATE=en_US.utf8 && export LC_COLLATE && ls /usr/share/man/man" + str(manual_type_cbtext_I.get_active() + 1) + " ) | sed 's/\." + str(manual_type_cbtext_I.get_active() + 1) + ".*gz$//' | grep -v '^[A-Za-z0-9]'"
                # print dynamic_command
                result.set_text("")
                execute_command_I(dynamic_command)
            elif starting_with_cbtext_II.get_active_text() == 'all':
                dynamic_command = "(LC_COLLATE=en_US.utf8 && export LC_COLLATE && ls /usr/share/man/man" + str(manual_type_cbtext_I.get_active() + 1) + " ) | sed 's/\." + str(manual_type_cbtext_I.get_active() + 1) + ".*gz$//' | grep -v '^$'"
                # print dynamic_command
                result.set_text("")
                execute_command_I(dynamic_command)
            else:
                dynamic_command = "(LC_COLLATE=en_US.utf8 && export LC_COLLATE && ls /usr/share/man/man" + str(manual_type_cbtext_I.get_active() + 1) + " ) | sed 's/\." + str(manual_type_cbtext_I.get_active() + 1) + ".*gz$//' | grep -i '^" + starting_with_cbtext_II.get_active_text() + "'"
                # print dynamic_command
                result.set_text("")
                execute_command_I(dynamic_command)
        elif not manual_type_cbtext_I.get_active_text():
            result.set_text("Please Select Manual Type First !")


    def select_manual_cbtext_3_changed(self, comboboxtext):
        if select_manual_cbtext_III.get_active_text():
            if manual_type_cbtext_I.get_active_text():
                dynamic_command = "man --sections=" + str(manual_type_cbtext_I.get_active() + 1) + " " + select_manual_cbtext_III.get_active_text() + "|tee"
                # print dynamic_command
                execute_command_II(dynamic_command)
            else:
                dynamic_command = "man " + select_manual_cbtext_III.get_active_text() + "|tee"
                # print dynamic_command
                execute_command_II(dynamic_command)
        else:
            result.set_text("")


    def detailsbutton(self, button):
        ouraboutwindow.set_transient_for(window)
        ouraboutwindow.run()
        ouraboutwindow.hide()
        # ouraboutwindow.destroy()


builder = Gtk.Builder() 
builder.add_from_file("/usr/lib/helpman/helpman.glade")
# builder.add_from_file("helpman.glade")  
builder.connect_signals(Handler()) 
window = builder.get_object("window1") 
textview = builder.get_object("textview1")
textbuffer = textview.get_buffer()
# textview.modify_font(Pango.FontDescription('Verdana 14'))

# bgcolor = Gdk.RGBA()
# bgcolor.parse('#edd2a4')

# fgcolor = Gdk.RGBA()
# fgcolor.parse('#AACCFF')

# crcolor = Gdk.RGBA()
# crcolor.parse('#FFFFFF')

# textview.override_background_color(Gtk.StateFlags.NORMAL, bgcolor)

# textview.override_color(Gtk.StateFlags.NORMAL, fgcolor)

# textview.override_cursor(crcolor, fgcolor)

manual_type_cbtext_I = builder.get_object("manual_type_cbtext_1")
# manual_type_cbtext_I.modify_font(Pango.FontDescription('Verdana 14'))
manual_type_cbtext_I.grab_focus()

starting_with_cbtext_II = builder.get_object("starting_with_cbtext_2")
# starting_with_cbtext_II.modify_font(Pango.FontDescription('Verdana 14'))

select_manual_cbtext_III = builder.get_object("select_manual_cbtext_3")
# select_manual_cbtext_III.modify_font(Pango.FontDescription('Verdana 14'))

# Following specifies the combo box text values and populates the same

default_textI = ["Executable programs or shell commands", "System calls (functions provided by the kernel)", "Library calls (functions within program libraries)", "Special files (usually found in /dev)", "File formats and conventions eg /etc/passwd", "Games", "Miscellaneous (including  macro  packages  and  conventions)", "System administration commands (usually only for root)"]

for x in default_textI:
    # print x
    manual_type_cbtext_I.append_text(x)

default_textII = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "[0-9]", "others", "all"]

for y in default_textII:
    starting_with_cbtext_II.append_text(y)

result = builder.get_object("result1")
# result.modify_font(Pango.FontDescription('Verdana 14'))

smentry = builder.get_object("smentry1")
# smentry.modify_font(Pango.FontDescription('Verdana 14'))

# Following sets the theme for the widgets

# load CSS
style_provider = Gtk.CssProvider()
css = open('/usr/lib/helpman/helpman.css')
css_data = css.read()
css.close()
style_provider.load_from_data(bytes(css_data.encode()))
Gtk.StyleContext.add_provider_for_screen(Gdk.Screen.get_default(),style_provider,Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)

textview.get_style_context().add_class("textview_theme")
result.get_style_context().add_class("result_theme")
manual_type_cbtext_I.get_style_context().add_class("font_theme")
starting_with_cbtext_II.get_style_context().add_class("font_theme")
select_manual_cbtext_III.get_style_context().add_class("font_theme")
smentry.get_style_context().add_class("font_theme")

ouraboutwindow = builder.get_object("aboutdialog1")
window.connect("delete-event", Gtk.main_quit) 
window.show_all() 
Gtk.main()
