# Copyright (C) 2005 Insecure.Com LLC.
#
# Author: Luis A. Bastiao Silva <luis.kop@gmail.com>
#
# 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; either version 2 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, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA


import gtk 

import sys
# Testing at devel 
from os.path import split, join

from umitCore.Paths import Path
Path.set_umit_conf(join(split(__file__)[0], 'config', 'umit.conf'))
#END DEV TEST
options = Path.options
profile_editor = Path.profile_editor
#XXX This path is too wrong 
sys.path.append("selectborder")
from WidgetsPlace import EditArea
from WrapperWidgets import NotebookLabel, SpecialHBox
from higwidgets.higscrollers import HIGScrolledWindow
from higwidgets.hignotebooks import HIGNotebook
from higwidgets.higlabels import HIGSectionLabel, HIGEntryLabel

from umitCore.NmapCommand import CommandConstructor
from umitCore.UmitConf import Profile, CommandProfile
from umitGUI.OptionBuilder import *
from higwidgets.higboxes import HIGVBox
from umitCore.Logging import log
from umitCore.I18N import _
from higwidgets.higtables import HIGTable


TARGET_STRING = 0
TARGET_ROOTWIN = 1

target = [
    ('STRING', 0, TARGET_STRING),
    ('text/plain', 0, TARGET_STRING),
    ('application/x-rootwin-drop', 0, TARGET_ROOTWIN)
]


from ProfileCore import ProfileCore, ProfileOption
from Command import Command, TwiceCommand, command_manager

class CommandAddRemoveLabel(TwiceCommand, Command):
    ''' 
    Add or Remove Label from Title pages of NotebookEditable 
    ###
    trik : state is a inicial value if it is remove or add.
    '''
    def __init__(self, widget, text, state):
        TwiceCommand.__init__(self, state)
        Command.__init__(self, _('Add Label'))
        self._widget = widget
        self._text = text 
        
    
    def _add_label(self):
        self._widget.unload_voidplace()
        self._widget.set_text(self._text) 
        log.debug('Adding label')
    _execute_1 = _add_label
    def _remove_label(self):
        self._widget.voidplace()
        log.debug('Removing label, Adding Void Place')
    _execute_2 = _remove_label



class BoxEditable(HIGVBox):
    def __init__(self, section_name, profile):
        '''
        A Box Editable contains a options of each tab
        @param section_name: section name <tab>
        @type section_name: str 
        @param profile: A class that view and modify xml file 
        @type profile: ProfileCore
        '''
        HIGVBox.__init__(self)

        self._profile = profile
        self._table = HIGTable()
        self._options = self._profile.get_section(section_name)
        self._fill_table()
	
	box_tmp = HIGVBox()
	box_tmp.pack_start(self._table, False, False)
	self._sw = HIGScrolledWindow()
	#self._sw.set_size_request(400,200)
	vp = gtk.Viewport()
	vp.add(box_tmp)
	vp.set_shadow_type(gtk.SHADOW_NONE)
	self._sw.add(vp)
	self.pack_start(self._sw, True, True)
	self._old_selected = None 
    #Private API 
    def _fill_table(self):

	k = 0
        for i in self._options:
	    t = SpecialHBox()
	    type = i.get_type()
	    if type== 'option_check':
		tmp_widget = OptionCheckIcon(i.get_label(),i.get_option(),'asddas')
		t.pack_start(tmp_widget)
		t.connect('button-press-event', self._button_press_event)
	    elif type == 'option_list': 
		eventbox = gtk.EventBox()
		label = HIGEntryLabel(i.get_label())
		eventbox.add(label)
		tmp_widget = OptionList()
		for j in i.get_option_list():
		    d = {}
		    d['name'] = j 
		    tmp_widget.append(d)
		t.pack_start(eventbox)		
		t.pack_start(tmp_widget)
		#t.drag_source_set(gtk.gdk.BUTTON1_MASK |
						  #gtk.gdk.BUTTON3_MASK,
						  #target, 
						  #gtk.gdk.ACTION_COPY |
						  #gtk.gdk.ACTION_MOVE)
		#t.connect('drag_data_get', self.source_drag_data_get)
		t.connect('button-press-event', self._button_press_event)
		
		
	    self._table.attach(t, 0,2, k,k+1)
	    k =k +1
    def source_drag_data_get(self, btn, context, selection_data, info, time):
        selection_data.set(selection_data.target, 8, "I'm Data!")


    def _button_press_event(self,widget, event):
	widget.set_select(True)
	if widget == self._old_selected :
	    return 
	widget.do_draw()
	if self._old_selected != None:
	    self._old_selected.set_select(False)
	log.debug('drawing')
	self._old_selected = widget
        
    

class NotebookEditable(HIGNotebook):
    '''
    Editable Notebook to Edit Profile Editor
    '''
    def __init__(self):
        HIGNotebook.__init__(self)
        self.sections_widgets = {}
        #self.connect('key-press-event', self.on_key_press)
        self._old_select = None 

    
    def reset(self):
        pass
    
    def load_data(self):
        self.profile = CommandProfile()
        options_used = {}
        
        self.constructor = CommandConstructor(options_used)
        self.options = ProfileCore(profile_editor)  
        i = 0
        for tab in self.options.groups:
            self.create_tab(tab, self.options.section_names[tab], 
                            self.options.tabs[tab], i)
            i = i+1 
    def create_tab(self, tab_name, section_name, tab, number):
        
        box = BoxEditable(tab_name, self.options)
        label = NotebookLabel(tab_name)
        #eventbox = gtk.EventBox()

        #eventbox.add(label)
        label.set_flags( label.flags() |  gtk.CAN_FOCUS)
        label.connect('key-press-event', self.on_key_press)
        label.connect('button-press-event', self.on_button_press)  

        
        label.connect('drag_data_received', self.label_drag_data_received)
        label.drag_dest_set(gtk.DEST_DEFAULT_ALL, target[:-1],
                            gtk.gdk.ACTION_COPY | gtk.gdk.ACTION_MOVE)
        #eventbox.show_all()
        label.show_all()
        self.sections_widgets[label] = number
        self.append_page(box, label)
    def on_button_press(self, widget, event):
        if self._old_select != None:
            self._old_select.set_select(False)
        widget.set_select(True)
        self._old_select = widget
        self.set_current_page(self.sections_widgets[widget])
        widget.grab_focus()
        return True
    def on_key_press(self, widget, event):
        _keyval = gtk.gdk.keyval_name(event.keyval)
        print _keyval
        if _keyval == "Delete":
            if self._old_select.is_voidplace():
                self._old_select.unload_voidplace()
                self.remove_page(self.get_current_page())
            else: 
                cmd = CommandAddRemoveLabel(self._old_select, 
                                            self._old_select.get_text(), False)
                command_manager.add_command(cmd)

        else: 
            self._old_select.unload_voidplace()
    def label_drag_data_received(self, w, context, x, y, data, info, time):
        print "received"

        if data and data.format == 8:
            print 'Received "%s" in label' % data.data
            context.finish(True, False, time)
            cmd = CommandAddRemoveLabel(self._old_select, 'New Label', True)
            command_manager.add_command(cmd)
            
            
        #else:
        #    context.finish(False, False, time)


class ProfileEdit(gtk.VBox):
    def __init__(self):
        gtk.VBox.__init__(self)

        
        #MAIN SCROLLED
        self._scroolledmain = HIGScrolledWindow()
        #NOTEBOOKEDITABLE :
        self.notebook = NotebookEditable()
        self.notebook.load_data()
        self.pack_start(self._scroolledmain, True, True)
        self._scroolledmain.add_with_viewport(self.notebook)
        self.show_all()
        self._edit_area = EditArea()
        
        
    def create_events(self):
        #....
        pass

        