#!/usr/bin/env python

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk, GObject, GLib, Gio, GdkPixbuf
import gettext
import re
import os
gettext.install("app-select", "/usr/share/locale")
        
class Error:
    def __init__(self, error):
        dlg = Gtk.MessageDialog(parent=None, flags=0, message_type=Gtk.MessageType.ERROR, buttons=Gtk.ButtonsType.OK, text="Error")
        dlg.set_title(_("Failed to updated"))
        dlg.format_secondary_text(error)
        dlg.run()
        dlg.destroy()

class add_mime(Gtk.Dialog):
    def on_cell_toggled(self, renderertoggle, treepath):
        self.all_mime_store[treepath][1] = not self.all_mime_store[treepath][1]
        
    def __init__(self, parent):
        super().__init__(title="%s" % _('app-select - mime editor - add mime'), transient_for=parent, flags=0)
        self.add_buttons(
            Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_ADD, Gtk.ResponseType.OK
        )

        self.set_default_size(640,480)
        
        sw = Gtk.ScrolledWindow()
        sw.set_hexpand(True)
        sw.set_vexpand(True)
        sw.show()
        
        self.all_mime_store = Gtk.ListStore(str,bool) 
        for line in open("/etc/mime.types", "r"):
            sline = line.strip()
            if not sline.startswith("#") and sline:
                mime_line = re.split(r'\t+', sline)
                mime_type = mime_line[0]
                self.all_mime_store.append([mime_type, False])
        
        treeview = Gtk.TreeView()
        treeview.set_model(self.all_mime_store)
        treeview.set_enable_search(True)
        for i, column_title in enumerate([_("Mime Type"), _("Select")]):
            if i == 1:
                renderertoggle = Gtk.CellRendererToggle()
                renderertoggle.connect("toggled", self.on_cell_toggled)
                column = Gtk.TreeViewColumn(column_title, renderertoggle, active=1)
            else:
                column = Gtk.TreeViewColumn(column_title, Gtk.CellRendererText(), text=i)
            column.set_visible(True)
            treeview.append_column(column)
        
        treeview.set_headers_visible(True)
        sw.add(treeview)
        treeview.show()
        
        vbox = Gtk.VBox()
        sw.add(vbox)
        vbox.show()
        
        for i in range(10):
            label = Gtk.Label()
            label.set_text("This is a test")
            vbox.pack_start(label, 0,0,0)
            label.show()

        box = self.get_content_area()
        box.add(sw)
        self.show_all()
        
         
class mainWindow(Gtk.Window):
    def apply(self,item):
        for row in self.store:
            if row[2] == True:
                mime_type = row[0].strip(" ")
                try: 
                    Gio.AppInfo.set_as_default_for_type(self.app_info, mime_type)
                except:
                    Error( _("Could not set %s as default for %s" % (self.app_file, mime_type)))
    
        if re.search("/*.*/.local/share/applications/", self.app_file):
            base_filename=os.path.basename(self.app_file)
            app_info_local=Gio.DesktopAppInfo.new_from_filename(self.app_file)
            app_info_system=Gio.DesktopAppInfo.new_from_filename("/usr/share/applications/%s" % base_filename)
            
            if Gio.AppInfo.equal(app_info_local, app_info_system):
                app_local_mtypes = str(app_info_local.get_supported_types())
                app_local_mtypes = app_local_mtypes.replace("'", "").replace("[", "").replace("]", "").replace(",",";")
                
                app_system_mtypes = str(app_info_system.get_supported_types())
                app_system_mtypes = app_system_mtypes.replace("'", "").replace("[", "").replace("]", "").replace(",",";")
                
                if app_local_mtypes == app_system_mtypes:
                    os.remove(self.app_file)
                
        self.close()
    
    def on_cell_toggled(self, renderertoggle, treepath):
        self.store[treepath][2] = not self.store[treepath][2]
        
    def write_file(self, new_mime_list, replace_mime):
        if re.search("/usr/*.*/applications/", self.app_file):
            app_file_basename=os.path.basename(self.app_file)
            os.system("cp %s ~/.local/share/applications/%s" % (self.app_file, app_file_basename))
            self.app_file = os.path.expanduser("~/.local/share/applications/%s" % app_file_basename)
            
        self.app_info = Gio.DesktopAppInfo.new_from_filename(self.app_file)
            
        with open(self.app_file, 'r', encoding='utf-8') as file:
            text = file.readlines()
        file.close()
            
        found=False
        for index, line in enumerate(text):
            if re.search("^MimeType=", line):
                found=True
                if replace_mime:
                    text[index] = "MimeType=%s\n" % new_mime_list
                else:
                    text[index] = "%s;%s\n" % (text[index].strip('\n'), new_mime_list)
        if not found:
            text.append("MimeType=%s\n" % new_mime_list)
        else:
            del found
            
        with open(self.app_file, 'w', encoding='utf-8') as file:
            file.writelines(text)
        file.close()
    
    def run_add_mime(self, widget):
        dialog = add_mime(self)
        response = dialog.run()
        new_mime_list=""
        
        if response == Gtk.ResponseType.OK:
            for row in dialog.all_mime_store:
                if row[1] == True:
                    mime_type = row[0].strip(" ")
                    default_app_info = Gio.AppInfo.get_default_for_type(mime_type, False)
                    if default_app_info:
                        default_app = default_app_info.get_name()
                    else:
                        default_app = "None"
                        
                    new_mime_list+="%s;" % row[0]
                    Gio.AppInfo.add_supports_type(self.app_info, row[0])
                    self.store.append([row[0], default_app, True])
                    
            self.write_file(new_mime_list, False)
        
        dialog.destroy()
        
    def run_remove_mime(self, widget):
        new_mime_list=""
        for row in self.store:
            if row[2] == True:
                mime_type = row[0].strip(" ")
                try: 
                    Gio.AppInfo.remove_supports_type(self.app_info, mime_type)
                    self.store.remove(row.iter)
                except:
                    Error(_("Could not remove %s from mime types for %s" %  (mime_type, self.app_file)))
            else:
                new_mime_list+="%s;" % row[0]
        
        self.write_file(new_mime_list, True)

    def __init__(self,mime_list,app_file,app_name):
        Gtk.Window.__init__(self)
        self.set_size_request(640,480)
        self.set_border_width(10)
        self.set_title(_(" App Select - mime editor"))
        self.show()
        
        self.app_file=app_file
        
        window_grid = Gtk.Grid()
        self.add(window_grid)
        window_grid.show()
        
        sw = Gtk.ScrolledWindow()
        sw.set_hexpand(True)
        sw.set_vexpand(True)
        window_grid.attach(sw, 1,1,3,1)
        sw.show()
        
        self.app_info = Gio.DesktopAppInfo.new_from_filename(self.app_file)
        
        self.store = Gtk.ListStore(str,str,bool)
        for i, item in enumerate(re.split(';', mime_list)):
            default_app_info = Gio.AppInfo.get_default_for_type(re.sub(' ', '', item), False)
            if default_app_info:
                default_app = default_app_info.get_name()
                self.store.append([item, default_app, False])
        
        self.treeview = Gtk.TreeView()
        self.treeview.set_model(self.store)
        self.treeview.set_enable_search(False)
        for i, column_title in enumerate([_("Mime Type"), _("Current default"),_("Set %s as default for mime type" % app_name)]):
            if i == 2:
                renderertoggle = Gtk.CellRendererToggle()
                renderertoggle.connect("toggled", self.on_cell_toggled)
                column = Gtk.TreeViewColumn(column_title, renderertoggle, active=2)
            else:
                column = Gtk.TreeViewColumn(column_title, Gtk.CellRendererText(), text=i)
            column.set_visible(True)
            self.treeview.append_column(column)
        
        self.treeview.set_headers_visible(True)
        sw.add(self.treeview)
        self.treeview.show()
        
        add_mime_button = Gtk.Button.new_from_icon_name("gtk-add", Gtk.IconSize(1))
        add_mime_button.connect("clicked", self.run_add_mime)
        window_grid.attach(add_mime_button, 1,2,1,1) 
        add_mime_button.show()
        
        remove_mime_button = Gtk.Button.new_from_icon_name("gtk-remove", Gtk.IconSize(1))
        remove_mime_button.connect("clicked", self.run_remove_mime)
        window_grid.attach(remove_mime_button, 2,2,1,1) 
        remove_mime_button.show()
        
        select = Gtk.Button.new_from_icon_name("gtk-apply", Gtk.IconSize(1))
        select.connect("clicked", self.apply)
        window_grid.attach(select, 3,2,1,1) 
        select.set_can_default(True)
        select.grab_default()
        select.show()
        
        self.connect("delete-event", Gtk.main_quit)
        Gtk.main()
