#-----------------------------------------#
# Include the source files                                                #
#-----------------------------------------#
source combo.tcl
source button_output.tcl
source submenu/instrument_submenu.tcl
source submenu/lightisol_submenu.tcl

#--------------------------------------#
# Initialize variables			  	#
#--------------------------------------#
set clicked 0
set color ""
set varname "alternate"
set but_default1 0
set but_default2 0
set but_default3 0
set but_default4 0


#--------------------------------------------------------------------------
# This procedure will popup a small menu to ask the user to insert the connection type, x y position and
# other information regarding the button they want to display on the screen
#--------------------------------------------------------------------------

proc but_small_popup { }  {


    #----------------#
    # Declare variables      #
    #----------------#
    global varname
    global clicked
    global but_color
    global color
    global but_name 
    global but_default1 but_default2 but_default3 but_default4
    

    #------------------------------------------
    # Create a new window
    #------------------------------------------
    set small .but_small_popup

    if [winfo exists $small] {destroy $small}
    global env
    set env(DISPLAY) :0
    toplevel $small  -width 20c -height 95m
    wm title $small "Creating Button"

    #-------------------------------------------#
    # Creating Widgets                      	#  		                                             #
    #-------------------------------------------#

    label $small.connection_label \
        	-text Connection
    label $small.color_label \
        	-text Color
    label $small.name_label \
    	-text Name

    #---------------------------#
    # Create the list of name for button        #
    #---------------------------#
    button_name_combobox

    entry $small.connection_name  \
    	-textvariable conn_name -bg white
    button $small.arrow \
    	-command {button_add_output}

    #------------------------------------#
    # Create Color combobox called from "combo.tcl"     #
    #------------------------------------#
    color_combobox

    #---------------------------------------------------------------

    proc show_choices { parent vname args } {

       set f [frame $parent.choices -borderwidth 5]
       set b 0
       foreach item $args {
          radiobutton $f.$b -variable $vname \
             -text $item -value $item -command $item
             pack $f.$b -side left
             incr b
       }
       place $f -x 104 -y 140

    }

    #---------------------------------------------------------------

    set varname alternate
    show_choices $small varname alternate momentary

    #---------------------------------------------------------------

    label $small.type_label \
         	-height 0 -text Type
    frame $small.pos_frame \
         	-borderwidth 2 -height 65 -relief groove \
        	-width 135
    label $small.pos_frame.xlabel \
         	-height 0 -text x
    label $small.pos_frame.ylabel \
         	-text y
    entry $small.pos_frame.xentry \
        	-background white \
        	-textvariable sp_xentry -width 93
    entry $small.pos_frame.yentry \
        	-background white \
        	-textvariable sp_yentry -width 93
    label $small.position_label \
         	-text Position
    label $small.button_title \
        	-fg blue -relief groove -text "Button"
    button $small.add_but \
        	-command {add_button} -text Ok
    button $small.remove_but \
        	-command {remove_button $but_name 1} -text Remove
    button $small.close \
        	-command {destroy .but_small_popup} -text Close

    #---------------------------------------------------------------
    # Bind the left mouse button to display the mouse
    # coordinate upon released
    #---------------------------------------------------------------

    bind .ventana <ButtonRelease-1> {
    	global sp_xentry sp_yentry
     	set sp_xentry %x
     	set sp_yentry %y
    }	
        	

    #-------------------------------------------#
    # Default Frame				#
    #-------------------------------------------#

    label $small.default_label \
    	-text "Default" -relief groove -fg blue
    frame $small.default_frame \
        -borderwidth 2 -height 130 -relief groove -width 225

    label $small.default_frame.default1label \
        -text "Power Up"
    label $small.default_frame.default2label \
        -text "On Deck"
    label $small.default_frame.default3label \
        -text "10-100 M"
    label $small.default_frame.default4label \
        -text ">100 M"

    entry $small.default_frame.default1 \
        -background white -textvariable but_default1 
    entry $small.default_frame.default2 \
        -background white -textvariable but_default2
    entry $small.default_frame.default3 \
        -background white -textvariable but_default3
    entry $small.default_frame.default4 \
        -background white -textvariable but_default4


	
	#--------------------------------------------------------------------------#
	# Bind the entries to add / update info when user press Enter
	#--------------------------------------------------------------------------#
	    
     	for { set i 1 } { $i < 5 } { incr i } {
    		bind $small.default_frame.default$i <Return> {
    			add_button
		}
	}



       	
    #####################
    # SETTING GEOMETRY #
    #####################

    #-------------------------------------------#
    # Default Frame				#
    #-------------------------------------------#

    place $small.default_label \
	-x 350 -y 10 -width 195 -height 25
    place $small.default_frame\
        -x 350 -y 50 -width 195 -height 130

    place $small.default_frame.default1label \
        -x 5 -y 20 -width 80
    place $small.default_frame.default2label \
        -x 5 -y 45 -width 80
    place $small.default_frame.default3label \
        -x 5 -y 70 -width 80
    place $small.default_frame.default4label \
        -x 5 -y 95 -width 80

    place $small.default_frame.default1 \
        -x 80 -y 20 -width 90
    place $small.default_frame.default2 \
        -x 80 -y 45 -width 90
    place $small.default_frame.default3 \
        -x 80 -y 70 -width 90
    place $small.default_frame.default4 \
        -x 80 -y 95 -width 90



    #-------------------------------------#    	
    # The title, name, connection, color and type label    #
    #-------------------------------------#
    place $small.button_title \
        	-x 15 -y 10 -width 300 -height 25
    place $small.name_label \
    	-x 10 -y 50
    place $small.connection_label \
        	-x 10 -y 80
    place $small.color_label \
        	-x 10 -y 110
    place $small.type_label \
        	-x 10 -y 145

    #-------------------------------------------#
    # The name, connection, color and type 	#
    # entry or combobox     			#
    #-------------------------------------------#               	    	

    place $small.connection_name \
    	-x 105 -y 80
    place $small.arrow \
	-x 253 -y 80 -height 23

    #-------------------------#			    	
    # The label 'Position' for the frame    #
    #-------------------------#	
    place $small.position_label \
        	-x 10 -y 170

    #------------------------------------#    	 	
    # The frame 'Position' and its x y label and entries    #
    #------------------------------------#    	 	
    place $small.pos_frame \
        	-x 10 -y 190 -width 135 -height 75
    place $small.pos_frame.xlabel \
        	-x 10 -y 10
    place $small.pos_frame.ylabel \
        	-x 10 -y 35
    place $small.pos_frame.xentry \
        	-x 30 -y 10 -width 93 -height 22
    place $small.pos_frame.yentry \
        	-x 30 -y 35 -width 93 -height 22

    #------------------------------------#    	 	
    # The 'Add', 'Remove', and 'Close' buttons              #
    #------------------------------------#    	 	
    place $small.add_but -width 70 -height 50 \
        	-x 170 -y 210
    place $small.remove_but -width 70 -height 50 \
        	-x 250 -y 210
    place $small.close -width 70 -height 50 \
        	-x 330 -y 210


    #---------------------------------------------------------------

	
    proc momentary { } {
       global varname
       set varname "momentary"
       puts "Momentary button is selected here"
    }
        	
    proc alternate { } {
       global varname
       set varname "alternate"
       puts "Alternate button is selected here"

    }



    #---------------------------------------------------------------

     	
    #------------------------------------------------------------------
    # This procedure will add button to the main menu
    # Everytime we add a new button, we increment the counter
    # The purpose of having 'but_count' is so that we can assign
    # different name to the button easily and efficiently
    #------------------------------------------------------------------


    proc add_button { } {

        #--------------------#
        # Declare the variables         #
        #--------------------#

        global but_name
        global sp_xentry
        global sp_yentry
        global but_color
        global varname
        global clicked
        global vbut
        global conn_name
        global board
        global elnum
        global but_default1 but_default2 but_default3 but_default4


        #-----------------#
        # Initialize variables        #
        #-----------------#
        set vbut .ventana.editor.b$but_name


       #----------------------------------------------#	      	
       # Check if the user did not forget to insert name or connection       #
       #----------------------------------------------#

       if {$but_name == "" } {
       	puts "Please fill in the Name field "
       	return
       }

       if {$conn_name == "" } {
       	puts "Please select in the Connection field"
       	return
       }
 	
       if { $sp_xentry == "" } {
       	set sp_xentry 0
       }

       if { $sp_yentry == "" } {
       	set sp_yentry 0
       }


       #------------------------------------------------------------
       # Get the board and element number from the connection string passed
       #------------------------------------------------------------
       set board [get_board_number $conn_name]
       set elnum [lindex $conn_name 2]
       set type [check_out_db $but_name $board $elnum]







       #------------------------------------------------#
       # Send the default down to database		#
       #------------------------------------------------#

       # If it is a Gesout board, then add 100 for element number
       # Else, if it is MPL, add 200 for element number	

       if {$board == 0} {
       		set def_enum [expr {$elnum + 100}]
       } else {
       		set def_enum [expr {$elnum + 200}]
       }

       set bdef "$but_default1:$but_default2:$but_default3:$but_default4"
       send_io_elem_info 1 1 $def_enum none $bdef 0 0 0 0 0 0 0 0 0 0 0 none grey 0 0 1			
       send_out_list_info 1 1 $def_enum "$board|$elnum|"
       send_default_down 1 1 $def_enum








       #------------------------------------------------#	
       # Checking if the button has already been used or mapped before      #
       #------------------------------------------------#
           	
           	if {$type > 0 && $type < 9 } {               	
             	
           		#---------------------#
             	# Exists in OUTPUT database   #
             	#---------------------#                    	
            		set status [tk_dialog  .warning { } {The button has already been used / mapped in Output database. Please Remove it first } warning 0 {Close } ]
       		switch $status {0 {puts "Cancel"; return} }             	
       	
       	}
                                                    	
            	if { $type == 0 || $type == 90}  {
            	
            		#--------------------------------------------#
       	    	# add it to Button database, user just want to reposition button   #
       	    	#--------------------------------------------#
            		set temp_vbut .ventana.editor.b[get_button_name $board $elnum]
            		destroy $temp_vbut
            		add_to_button_db $but_name $varname $board $elnum $sp_xentry $sp_yentry $but_color 0 1
            	
            	}

            	#--------------------------------#
            	# Same name but different connection,           #
            	# can't do this.....display an error message	#
            	#--------------------------------#
             if {$type == 91} {
             		global env
             		set env(DISPLAY) :0
               	set status [tk_dialog  .warning { } {The Connection has already been used by other button. Please Remove it first } warning 0 {Close } ]
       		        switch $status {0 {puts "Cancel"; return} }             	
              }

            #---------------------------------------------#
            # Same connection different name, user just want to rename it.     #
            # Destroy old button and then overwrite the name                       #
            #---------------------------------------------#
            if {$type == 92} {	
            		set temp_vbut .ventana.editor.b[get_button_name $board $elnum]
            		destroy $temp_vbut
            		add_to_button_db $but_name $varname $board $elnum $sp_xentry $sp_yentry $but_color 0 1
                  		
            }

             #--------------------------------#
             # Show where the connection has exist          #
             # (if it does exist somewhere else)  		#
             #--------------------------------#
             #set result_string [show_connection_existence $type]
             #puts "but_small_popup.tcl: Button has already exist in $result_string"
             	

             #-------------------------------------#
             # This will create the button and place it on screen     #
             #-------------------------------------#
             creating_button


    # end of the procedure "add_button"	
    }








    #---------------------------------------------------#
    # This process can be called when we open the file in the                      
    # beginning (since we don't  want to add button to database                    
    # again by calling "add_button). Therefore, we need a proc                     
    # that only draws button to the screen                                                 
    #---------------------------------------------------#

    proc creating_button { } {

    	global but_name
   	global sp_xentry
	global sp_yentry
        global but_color
        global color
        global varname
        global clicked
        global vbut
        global conn_name
        global board
       	global elem_num
       	

        set vbut .ventana.editor.b$but_name
        global $conn_name
	

        # Setting the default color to grey
        if {$but_color != "grey" && $but_color != "red" && $but_color != "green" && $but_color != "blue" && $but_color != "purple" } {
       	 	set but_color "grey"
       	}         	 	

        if {$color != "" && $color != " " && $color != 0  &&  $color != 1} {
       	    	set but_color $color
       	    	set color ""
        }
       	
       #----------------------------------------------	      	
       # Check if the user did not forget to insert name or connection
       #----------------------------------------------

       if {$but_name == "" } {
       	puts "Please fill in the Name field "
       	return
       }


       if {$conn_name == "" } {
       	puts "Please select in the Connection field"
       	return
       }
 	

 	#------------------------------------------------------------
       	# If the user wants a button that stays pressed when clicked once (Alternate)
       	#------------------------------------------------------------
       	
       	
       	#puts "but_small_popup.tcl : type of button is $varname"
       	
       	if {$varname == "alternate"} {
       	
       	       	global $conn_name
       	
       	       	#-------------------------#
       	       	# Create an Alternate button	#
       	       	#-------------------------# 	
       		button $vbut -text $but_name -relief flat \
       			-bg $but_color -activebackground $but_color \
       			-width 10 -wraplength 80
       		
       		
       			
       		set state [get_button_state $board $elem_num]
       		set $conn_name $state
       		 	
       		 bind $vbut <ButtonRelease-1>  {
       		 	
       		 	set vbut %W
       		 	set name [lindex [$vbut configure -text] 4]
       		 	set conn [get_button_connection $name]
       		 	
       		 	#puts "name is : $name  "
       		 	set connection [split $conn |]              		 	       		 	
       		 	set brd [lindex $connection 0]
       		 	set elem [lindex $connection 1]
       		 	       		 	       		 	
       		 	#-------------------#
       		 	# send it down to bottom      #
       		 	#-------------------#
       		 	send_alternate_but_down $brd $elem        		 	
       		 	set state [get_button_state $brd $elem]       		 	
       		 	
       		 	if {$state == -1} {
       		 		puts "but_small_popup.tcl : Invalid state"
       		 	}
       		 	
       		 	#puts "------------------$state here --------------"
       		 	
       		 	#-----------------------------------------------#
       		 	# Set the new state and                      	#
       		 	#-----------------------------------------------#           		 	
       		 	
       		 	set_button_state $brd $elem $state
       		 	
       		 	#-----------------------------------------------#           		 	
       		 	# update the "Instrument" switches            	#
       		 	#-----------------------------------------------#           		 	
       		 	
       		 	update_switches $brd $elem $state
       		 	
       		 	#-----------------------------------------------#           		 	
       		 	# Update the light isolation switches		#
       		 	#-----------------------------------------------#           		 	
       		 	
       		 	update_lightisol_switches $brd $elem $state
       		 	
       		 	
       		 	#-----------------------------------------------#           		 	
       		 	# Update the button on the other screen		#
       		 	# (if it does exist)                         	#
       		 	#-----------------------------------------------#       		 	
       		 	update_button $brd $elem
       		 	
       		 	
       		 	
       		 	
       		 	if {$state == 0} {
       		 		set bclr [lindex [get_button_color_type $brd $elem] 0]
       		 	
       		 	        	if { $bclr == -1 || $bclr == ""} {
       		 	        		set bclr grey
       		 	        		$vbut configure -bg $bclr
       		 	            		$vbut configure -activebackground $bclr
       		 	
       		 	        	} else {          		 	
       		 	             	$vbut configure -bg $bclr
       		 	             	$vbut configure -activebackground $bclr
       		 	
       		 	        	}
       		 	} else {
       		 		#set state 0
       		 		$vbut configure -bg #ffffff
       		 		$vbut configure -activebackground #ffffff
       		 	
       		 	}
       		 	
       		 }
       			
       		
       	       	
       	} else {
       	             #----------------------------#
       	   	# Create the Momentary button here       #
       	   	#----------------------------#
       		button $vbut -text $but_name -bg $but_color \
       			-width 10 -wraplength 80 -activebackground $but_color
       		
       		#--------------------------------------#
       		# Make it change state when pressed down,		#
       		# and change again when released                	#
       		#--------------------------------------#
       		
       		bind $vbut <ButtonPress-1>  {
       		
       		 	set vbut %W
       		 	set name [lindex [$vbut configure -text] 4]
       		 	set conn [get_button_connection $name]
       		 	set connection [split $conn |]
       		 	
       		 	set the_board [lindex $connection 0]
       		 	set the_enum [lindex $connection 1]
       		 	
       		 	#---------------------------#
       		 	# Send the command down to sub        #
       		 	#---------------------------#		 	
       		 	send_momentary_but_down $the_board $the_enum 1
       		 	
       		 }
       			
       		 bind $vbut <ButtonRelease-1>  {
       		 	       		 	
       		 	set vbut %W
       		 	set name [lindex [$vbut configure -text] 4]
       		 	set conn [get_button_connection $name]
       		 	set connection [split $conn |]
       		 	
       		 	set the_board [lindex $connection 0]
       		 	set the_enum [lindex $connection 1]
       		 	
       		 	#---------------------------#
       		 	# Send the command down to sub        #
       		 	#---------------------------#	
       		 	send_momentary_but_down $the_board $the_enum 0
       		 }
       			
       	
       	}

   #-----------------------#    	
   # place it in the main screen        #
   #-----------------------#
   place $vbut -in .ventana.editor \
	-x $sp_xentry -y $sp_yentry -height 35
	

    #end of proc "creating_button"
    }





    #---------------------------------------#
    # Remove button from the screen and from database       #
    #---------------------------------------#

    proc remove_button {name screen} {

       global but_name
       global conn_name

       set conn [get_button_connection $but_name]
       puts "conn here is $conn"
       set connection [split $conn |]


       set board [lindex $connection 0]
       set elem_num [lindex $connection 1]

       if { $board == 0 } {
       	set conn_name "Dig Gesout [lindex $connection 1]"
       }
       if { $board == 1 } {
       	set conn_name "Dig MPL [lindex $connection 1]"
       }		 	

       set rbut  .ventana.editor.b$but_name

      #------------------------------------------#
      # Remove button from the screen and database if exists 	#
      #------------------------------------------#
       if [ winfo exists $rbut] {
             destroy $rbut                                                                               	
              	
             #------------#
             # Screen = 1	#
             #------------#
       	remove_button_from_db $board $elem_num 1

       }  else {

       	#-------------------------#
       	# If the button does not exist	#
       	#-------------------------#
       		
             global env
             set env(DISPLAY) :0
       	set status [tk_dialog .warning { } {The button you are trying to remove does not exist ! } \
			warning 0 {Close} ]
       	switch $status {
		0 return
       	}

       # end 'else'
       }


    # end of remove_button procedure
    }


# end of the procedure but_small_popup
}


#--------------------------------------#
# This procedure will convert the type of button	#
# into integers (which are going to be saved in db)	#
#--------------------------------------#

proc get_board_number { conn } {

	if {[lindex $conn 1] == "Gesout"} {
		return 0
	}
	if {[lindex $conn 1] == "MPL"} {
		return 1
	}
	if {[lindex $conn 1] == "Gesdac"} {
		return 2
	}


}


#--------------------------------------------------#
# Bind the button to the "Instrument" switches     #
#--------------------------------------------------#
    	
proc update_switches { board elem_num state } {

   	global im fm

   	#------------------#
   	# If it is not MPL board      #
   	#------------------#
   	if { $board != 1 } { return }
   	
   	if { $elem_num >= 2 && $elem_num <= 8 } {
   		
   		#----------------------------------------#
   		# the index is 1 less than the channel / element number     #
   		#----------------------------------------#
   		set index [incr elem_num -1]
   		set im($index) $state	
   	    	return
   		
   	}
   	
    	
            if { $elem_num >= 14 && $elem_num <= 18 } {
   		
   		#----------------------------------------#
   		# the index is 1 less than the channel / element number     #
   		#----------------------------------------#
   		set index [incr elem_num -13]
   		set fm($index) $state	
   	    	#puts "fm($index) $state" 	
   	    	return	
   	}
   	
              if { $elem_num >= 20 && $elem_num <= 32 } {
   		
   		#----------------------------------------#
   		# the index is 1 less than the channel / element number     #
   		#----------------------------------------#
   		set index [incr elem_num -14]
   		set fm($index) $state	
   	    	#puts "fm($index) $state" 		
   	    	return
   	}
   	
}

#-------------------------------------------------------#
# Bind the button to the "Light Isolation" switches     #
#-------------------------------------------------------#

proc update_lightisol_switches { board elem_num state } {

 	global li1 li2 li3 li4 li5 li6 li7 li8

 	#-------------------------------------------------------#
 	# Right now, the light isolation channel is hard coded 	#
 	# at Gesout (board 0), channel 57 to 64			#
 	# If it is ON (state == 1), then we should turn on the 	#
 	# light isolation switches and isolate the light	#
 	#-------------------------------------------------------#
 	
        if {$board == 0 && $elem_num >= 57 && $elem_num <= 64 } {
   		

        	#-------------------------------------------------------#
        	# For now, we do not want to use Gesout 60 		#
         	# to isolate the light #4 because it is mapped		#
         	# to toolsled. Therefore, if the elem_num is 60         #
         	# then we just return and do not update the light 	#
         	# isolation switches					#
         	#-------------------------------------------------------#
        	
         	if {$elem_num == 60} {return}

        	set index [expr {$elem_num - 56 }]
        	
        	# Turn on the light isolation switch
        	set li$index $state
        	
        	# Isolate the light if isolation state is ON
        	if { $state == 1 } { isolate $index }

        }
}


