#-----------------------------------------#
# Include the source files                                                #
#-----------------------------------------#
source combo2.tcl
source button_output2.tcl
source submenu/instrument_submenu2.tcl
source submenu/update_button.tcl

#-----------------------------------------#
# Initialize variables			  #
#-----------------------------------------#
set clicked 0
set color2 ""
set varname2 "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_popup2 { }  {


    global varname2


    #----------------------------------------
    # Declare variables
    #----------------------------------------
    global clicked
    global but_color2
    global color2
    global but_name2
    global but_default1 but_default2 but_default3 but_default4


    #------------------------------------------
    # Create a new window
    #------------------------------------------
    set small2 .but_small_popup2

    if [winfo exists $small2] {destroy $small2}
    global env
    set env(DISPLAY) :0.1
    toplevel $small2  -width 20c -height 95m
    wm title $small2 "Creating Button"

    #-------------------------------------------
    # Creating Widgets
    #-------------------------------------------

    label $small2.connection_label \
        	-text Connection
    label $small2.color_label \
        	-text Color
    label $small2.name_label \
    	-text Name

    # Create list of button names
    button_name_combobox2


    entry $small2.connection_name  \
    	-textvariable conn_name2 -bg white	

    button $small2.arrow  \
    	-command {button_add_output2}

    # Create Color combobox called from combo2.tcl
    color_combobox2

    #---------------------------------------------------------------

    proc show_choices2 { 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 varname2 alternate
    show_choices2 $small2 varname2 alternate momentary

    #---------------------------------------------------------------


    label $small2.type_label \
         	-height 0 -text Type
    frame $small2.pos_frame \
         	-borderwidth 2 -height 65 -relief groove \
        	-width 135
    label $small2.pos_frame.xlabel \
         	-height 0 -text x
    label $small2.pos_frame.ylabel \
         	-text y
    entry $small2.pos_frame.xentry \
        	-background white \
        	-textvariable sp_xentry2 -width 93
    entry $small2.pos_frame.yentry \
        	-background white \
        	-textvariable sp_yentry2 -width 93
    label $small2.position_label \
         	-text Position
    label $small2.button_title \
        	-anchor center  -foreground blue -height 0 \
        	-relief groove -text Button -width 205
    button $small2.add_but \
        	-command {add_button2 } -text Ok
    button $small2.remove_but \
        	-command {remove_button2 $but_name2 2} -text Remove
    button $small2.close \
        	-command {destroy .but_small_popup2} -text Close

    #-------------------------------------------#
    # Default Frame				#
    #-------------------------------------------#

    label $small2.default_label \
    	-text "Default" -relief groove -fg blue
    frame $small2.default_frame \
        -borderwidth 2 -height 130 -relief groove -width 225

    label $small2.default_frame.default1label \
        -text "Power Up"
    label $small2.default_frame.default2label \
        -text "On Deck"
    label $small2.default_frame.default3label \
        -text "10-100 M"
    label $small2.default_frame.default4label \
        -text ">100 M"

    entry $small2.default_frame.default1 \
        -background white -textvariable but_default1
    entry $small2.default_frame.default2 \
        -background white -textvariable but_default2
    entry $small2.default_frame.default3 \
        -background white -textvariable but_default3
    entry $small2.default_frame.default4 \
        -background white -textvariable but_default4


    for { set i 1 } { $i < 5 } { incr i } {
    	bind $small2.default_frame.default$i <Return> {
    		add_button2
    	}
    }

    	
    #---------------------------------------------------------------
    # Bind the left mouse button to display the mouse
    # coordinate upon release
    #---------------------------------------------------------------

    bind .ventana2 <ButtonRelease-1> {
    	global sp_xentry2 sp_yentry2
    	#puts "%x %y"
     	set sp_xentry2 %x
     	set sp_yentry2 %y
    }	
        	
        	
    #---------------------------------------------------------------
    	
        	
        	
    ###################
    # SETTING GEOMETRY
    ###################
    #-------------------------------------------#
    # Default Frame				#
    #-------------------------------------------#

    place $small2.default_label \
	-x 350 -y 10 -width 195 -height 25
    place $small2.default_frame\
        -x 350 -y 50 -width 195 -height 130

    place $small2.default_frame.default1label \
        -x 5 -y 20 -width 80
    place $small2.default_frame.default2label \
        -x 5 -y 45 -width 80
    place $small2.default_frame.default3label \
        -x 5 -y 70 -width 80
    place $small2.default_frame.default4label \
        -x 5 -y 95 -width 80

    place $small2.default_frame.default1 \
        -x 80 -y 20 -width 90
    place $small2.default_frame.default2 \
        -x 80 -y 45 -width 90
    place $small2.default_frame.default3 \
        -x 80 -y 70 -width 90
    place $small2.default_frame.default4 \
        -x 80 -y 95 -width 90




    #-------------------------------------#    	
    # The title, name, connection, color and type label    #
    #-------------------------------------#

    place $small2.button_title \
        	-x 15 -y 10 -width 300 -height 25
    place $small2.name_label \
    	-x 10 -y 50
    place $small2.connection_label \
        	-x 10 -y 80
    place $small2.color_label \
        	-x 10 -y 110
    place $small2.type_label \
        	-x 10 -y 145

    #-------------------------------------------#
    # The name, connection, color and type 	#
    # entry or combobox     			#
    #-------------------------------------------#               	    	

    place $small2.connection_name \
    	-x 105 -y 80
    place $small2.arrow \
	-x 253 -y 80 -height 23
	
    #-------------------------#			    	
    # The label 'Position' for the frame    #
    #-------------------------#	
    	    	
    place $small2.position_label \
        	-x 10 -y 170

    #------------------------------------#    	 	
    # The frame 'Position' and its x y label and entries    #
    #------------------------------------#
    place $small2.pos_frame \
        	-x 10 -y 190 -width 135 -height 75
    place $small2.pos_frame.xlabel \
        	-x 10 -y 10
    place $small2.pos_frame.ylabel \
        	-x 10 -y 35
    place $small2.pos_frame.xentry \
        	-x 30 -y 10 -width 93 -height 22
    place $small2.pos_frame.yentry \
        	-x 30 -y 35 -width 93 -height 22

    #------------------------------------#    	 	
    # The 'Add', 'Remove', and 'Close' buttons              #
    #------------------------------------#    	 	
    place $small2.add_but -width 70 -height 50 \
        	-x 170 -y 210
    place $small2.remove_but -width 70 -height 50 \
        	-x 250 -y 210
    place $small2.close -width 70 -height 50 \
        	-x 330 -y 210


    #---------------------------------------------------------------

	
    proc momentary { } {
       global varname2
       set varname2 "momentary"
       #puts "momentary button is selected here"
    }
        	
    proc alternate { } {
       global varname2
       set varname2 "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_button2 { } {

    	# Declare the variables
    	global but_name2
   	global sp_xentry2
	global sp_yentry2
        global but_color2
        global varname2
        global clicked
        global v2but
        global conn_name2
        global board
        global elnum
        global varname2
        global but_default1 but_default2 but_default3 but_default4

        #puts "varname2 inside add_button2 procedure is $varname2"
        set v2but .ventana2.editor.b$but_name2



       #----------------------------------------------	      	
       # Check if the user did not forget to insert name or connection
       #----------------------------------------------

       if {$but_name2 == "" } {
       	puts "Please fill in the Name field "
       	return
       }


       if {$conn_name2 == "" } {
       	puts "Please select in the Connection field"
       	return
       }
 	
       if { $sp_xentry2 == "" } {
       	# puts "Please enter number in the x position entry"
       		set sp_xentry2 0
       }

       if { $sp_yentry2 == "" } {
       	# puts "Please enter number in the y position entry"
       		set sp_yentry2 0
       }


       #------------------------------------------------------------
       # Get the board and element number from the connection string passed
       #------------------------------------------------------------
       set board [get_board_number $conn_name2]
       set elnum [lindex $conn_name2 2]

       set type [check_out_db $but_name2 $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

       #puts "but_small_popup2.tcl : def_enum : $def_enum"
	#puts "but_small_popup2.tcl : sending down default : $bdef"	




       #----------------------------------------------	
       # 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_vbut2 .ventana2.editor.b[get_button_name $board $elnum]
            		destroy $temp_vbut2
            		add_to_button_db $but_name2 $varname2 $board $elnum $sp_xentry2 $sp_yentry2 $but_color2 0 2     	      	
       		
             }
             # Same name but different connection, can't do this.....display an error message
             if {$type == 91} {
             		global env
             		set env(DISPLAY) :0.1
               	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_vbut2 .ventana2.editor.b[get_button_name $board $elnum]
            		destroy $temp_vbut2
            		add_to_button_db $but_name2 $varname2 $board $elnum $sp_xentry2 $sp_yentry2 $but_color2 0 2     	      	
       		
            }

             # Show where the connection has exist (if it does exist somewhere else)
             	#set result_string [show_connection_existence $type]
             	#puts "but_small_popup2.tcl: Button has already exist in $result_string $type"
             	
             #--------------------------------------------------------#
             # This will create the button and place it on screen     #
             #--------------------------------------------------------#
             creating_button2


    # end of the procedure "add_button2"	
    }


    #---------------------------------------------------------------
    # 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_button2). Therefore, we need a proc
    # that only draws button to the screen
    #---------------------------------------------------------------

    proc creating_button2 { } {

    	global but_name2
   	global sp_xentry2
	global sp_yentry2
        global but_color2
        global color2
        global varname2
        global clicked
        global v2but
        global conn_name2
        global board
        global elem_num
       	

        set v2but .ventana2.editor.b$but_name2
        global $conn_name2
	

        # Setting the default color to grey
        if {$but_color2 != "grey" && $but_color2 != "red" && $but_color2 != "green" && $but_color2 != "blue" && $but_color2 != "purple" } {
       	 	set but_color2 "grey"
       	}         	 	

       	if {$color2 != "" && $color2 != " " && $color2 != 0 &&  $color2 != 1} {
       	    	set but_color2 $color2
       	    	set color2 ""
       	}
       	
       #----------------------------------------------	      	
       # Check if the user did not forget to insert name or connection
       #----------------------------------------------

       if {$but_name2 == "" } {
       	puts "Please fill in the Name field "
       	return
       }


       if {$conn_name2 == "" } {
       	puts "Please select in the Connection field"
       	return
       }
 	

 	#------------------------------------------------------------
       	# If the user wants a button that stays pressed when clicked once (Alternate)
       	#------------------------------------------------------------
       	
       	
       	if {$varname2 == "alternate"} {
       	       	
       	       	global $conn_name2
       	
       	       	 	       	
       		#-------------------------#
       	       	# Create an Alternate button	#
       	       	#-------------------------# 	
       		button $v2but -text $but_name2 \
       			-bg $but_color2 -relief flat -activebackground $but_color2 \
       			-width 10 -wraplength 80
       		
       		
       		
       		set state [get_button_state $board $elem_num]
       		set $conn_name2 $state
       		 	
       		 bind $v2but <ButtonRelease-1>  {
       		 	
       		 	set v2but %W
       		 	set name2 [lindex [$v2but configure -text] 4]
       		 	set conn [get_button_connection $name2]
       		 	
       		 	#puts "conn is : $conn  "
       		 	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_popup2.tcl : Invalid state"
       		 	}
       		 	
       		 	#puts "------------------$state here --------------"
       		 	
       		 	#-----------------------------------------------#
       		 	# Set the new state and                      	#
       		 	#-----------------------------------------------#           		 	
       		 	
       		 	set_button_state $brd $elem $state
       		 	
       		 	#-----------------------------------------------#           		 	
       		 	# update the "Instrument" switches            	#
       		 	#-----------------------------------------------#           		 	
       		 	       		 	
       		 	update_switches2 $brd $elem $state
       		 	
       		 	#-----------------------------------------------#           		 	
       		 	# Update the light isolation switches		#
       		 	#-----------------------------------------------#           		 	
       		 	
       		 	update_lightisol_switches2 $brd $elem $state
       		 	
       		 	#-----------------------------------------------#           		 	
       		 	# Update the button on the other screen		#
       		 	# (if it does exist)                         	#
       		 	#-----------------------------------------------#       		 	
       		 	update_button $brd $elem
       		 	
       		 	
       		 	
       		 	
       		 	if {$state == 0} {
       		 		#set state 1
       		 	        	set bclr [lindex [get_button_color_type $brd $elem] 0]
       		 	
       		 	        	if { $bclr == -1 ||  $bclr == "" } {
       		 	        		set bclr grey
       		 	        	 	$v2but configure -bg $bclr
       		 	             	$v2but configure -activebackground $bclr
       		 	
       		 	        	} else {
       		 	             	$v2but configure -bg $bclr
       		 	             	$v2but configure -activebackground $bclr
       		 	
       		 	        	}
       		 	
       		 	        	
       		 	} else {
       		 		#set state 0
       		 		$v2but configure -bg #ffffff
       		 		$v2but configure -activebackground #ffffff
       		 	}
       		 	
       		 }
       			
       		
       	       	
       	} else {
       	
       	   	#----------------------------#
       	   	# Create the Momentary button here       #
       	   	#----------------------------#
       		
       		button $v2but -text $but_name2 -bg $but_color2 -activebackground $but_color2\
       			-width 10 -wraplength 80
       		
       		#--------------------------------------#
       		# Make it change state when pressed down,		#
       		# and change again when released                	#
       		#--------------------------------------#
       		
       		bind $v2but <ButtonPress-1>  {
       		
       		 	set v2but %W
       		 	set name2 [lindex [$v2but configure -text] 4]
       		 	set conn [get_button_connection $name2]
       		 	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 $v2but <ButtonRelease-1>  {
       		 	       		 	
       		 	set v2but %W
       		 	set name2 [lindex [$v2but configure -text] 4]
       		 	set conn [get_button_connection $name2]
       		 	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 $v2but -in .ventana2.editor \
	-x $sp_xentry2 -y $sp_yentry2 -height 35
	


    #end of proc "creating_button2"
    }






    #-----------------------------------------------------------------

    proc remove_button2 {name screen} {

       global but_name2
       global conn_name2

       set conn [get_button_connection $but_name2]
       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_name2 "Dig Gesout [lindex $connection 1]"
       }
       if { $board == 1 } {
       	set conn_name2 "Dig MPL [lindex $connection 1]"
       }		 	

       set r2but  .ventana2.editor.b$but_name2

       if [ winfo exists $r2but] {
             destroy $r2but
       	
       	# Remove button from the database if exists (screen == 2)     	
       	remove_button_from_db $board $elem_num 2

       }  else {

              global env
              set env(DISPLAY) :0.1
       	set status [tk_dialog .warning2 { } {The button you are trying to remove does not exist ! } \
			warning 0 {Close} ]
       	switch $status {
		0 return
       	}

       # end 'else'
       }



    # end of remove_button2 procedure
    }

    #---------------------------------------------------------------


    proc clean_up2 { } {

    # Declare variables
    global but_name2
    global sp_xentry2
    global sp_yentry2

    # This statement below will clean up the name and position fields from old values

    .but_small_popup2.butname delete 0 [string length $but_name2]
    .but_small_popup2.connection_name delete 0 100

    .but_small_popup2.pos_frame.xentry delete 0 [string length $sp_xentry2]
    .but_small_popup2.pos_frame.yentry delete 0 [string length $sp_yentry2]

    }


# end of the procedure but_small_popup2
}


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_switches2 { 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_switches2 { 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 }

        	
        }
}