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

from subprocess import Popen, PIPE, STDOUT,call
from os import path,environ
from sys import platform
from urllib import unquote
from mimetypes import guess_type
from gi.repository import Gtk as gtk #GdkPixbuf, Nautilus, GObject
from gi.repository.GdkPixbuf import Pixbuf

class TagsManager:
	def __init__(self):
		self.d={}
		self.dtag={}
		cmd='tracker-tag -t'
		p=Popen(cmd,shell=True,stdin=PIPE, stdout=PIPE, stderr=STDOUT,close_fds=True)
		output = p.stdout.read()
		l=output.split('\n')
		while('' in l): l.remove('')
		if len(l)>3:
			for i in range(2,len(l),3):
				if i+2<len(l):self.d[l[i].strip()]=int(l[i+2][:l[i+2].find('f')])

		lk=[i for i in self.d.keys()]
		lk.sort()
		for tag in lk:
			if self.d[tag]<>0:
				cmd='tracker-tag -t -s'
				p=Popen(cmd,shell=True,stdin=PIPE, stdout=PIPE, stderr=STDOUT,close_fds=True)
				output = p.stdout.read()
				l=output.split('\n')
				ll= [unquote(i.strip()).decode('utf-8') for i in l]
				ini=ll.index(tag)
				lkini=lk.index(tag)
				if tag==lk[-1]:
					resp=ll[ini+1:]
					while('' in resp): resp.remove('')
				else:
					fin=ll.index(lk[lkini+1])
					resp=[ll[i] for i in range(ini+1,fin)]
				self.dtag[tag]=resp
		return

class Ventana:

    def delete_event(self, widget, event, data=None):
        return False

    def clic(self, widget, event, data=None):
        l=[]
        for i in self.todas.get_selection().get_selected_rows()[1]:
            t= self.todas.get_model().get_value(self.todas.get_model().get_iter(i), 0)
            l.append(t)
        if len(l)==1:
            lista_nueva=self.tm.dtag[l[0]]
        elif len(l)>1:
            lista_nueva=self.tm.dtag[l[0]]
            for i in l[1:]:
                ll=[]
                for f in self.tm.dtag[i]:
                    if f in lista_nueva: ll.append(f)
                lista_nueva=[f for f in ll]
        else:lista_nueva=[]
        self.files.get_model().clear()
        lista=[f.encode('utf-8')[7:] for f in lista_nueva]
        lf=[i for i in lista if path.isfile(i)]
        ld=[i for i in lista if not path.isfile(i)]
        lista_nueva=ld+lf
        for f in lista_nueva:
            mime_type= guess_type(path.basename(f))
            
            if mime_type[0]<>None:
                icon= 'gnome-mime-'+mime_type[0].replace('/','-')
            else:
                print f.encode('utf-8'),path.isfile(f)
                if path.isfile(f):icon='gtk-file'
                else:icon='folder'
            pixbuf = gtk.IconTheme.get_default().load_icon(icon, 48, 0)
            self.files.get_model().append([pixbuf,path.basename(f),f])
        return False

    def destroy(self, widget, data=None):
        gtk.main_quit()
    
    def open_file(self, iconview, ipath):
        model = iconview.get_model()
        iter = model.get_iter(ipath)
        filename = model.get_value(iter, 2)
        if platform == 'linux2':
            call(["xdg-open", filename])
        return
    
    def __init__(self):
        self.tm=TagsManager()
        self.window = gtk.Window()
        self.window.connect("delete_event", self.delete_event)
        self.window.connect("destroy", self.destroy)
        self.window.resize(600,400)
        self.window.set_title('search-tags')
        self.window.set_icon_name('search-tags')
        pixbuf = gtk.IconTheme.get_default().load_icon('search', 48, 0)
            
        self.window.set_icon(pixbuf)
        paned = gtk.HPaned()
      
        self.existentags = gtk.ListStore(str)
        tags=[i for i in self.tm.d.keys()]
        tags.sort()
        for t in tags:
            self.existentags.append([t])
        self.todas = gtk.TreeView(self.existentags)
        self.todas.get_selection().set_mode(gtk.SelectionMode.MULTIPLE)
        cell = gtk.CellRendererText()
        self.todas.connect("button_release_event", self.clic, None)
        column0=gtk.TreeViewColumn("Tags",cell, text=0)
        self.todas.append_column(column0) 
        scrolled_window = gtk.ScrolledWindow()
        scrolled_window.set_policy(gtk.PolicyType.AUTOMATIC, gtk.PolicyType.AUTOMATIC)
        scrolled_window.add_with_viewport (self.todas)
        paned.add1(scrolled_window)
        
        self.listfiles = gtk.ListStore(Pixbuf,str,str)
        self.files = gtk.IconView.new()
        self.files.set_model(self.listfiles)
        self.files.set_pixbuf_column(0)
        self.files.set_text_column(1)
        self.files.connect('item-activated', self.open_file)
        scrolled_window2 = gtk.ScrolledWindow()
        scrolled_window2.set_policy(gtk.PolicyType.AUTOMATIC, gtk.PolicyType.AUTOMATIC)
        scrolled_window2.add_with_viewport (self.files)
        paned.add2(scrolled_window2)
            
        self.window.add(paned)
        self.window.show_all()

    def main(self):
       gtk.main()

if __name__ == "__main__":
    hello = Ventana()
    hello.main()

