module Defaults



  DEFS= Hash.new
  DEFS['Servers']= ['igs.joyjoy.net','lgs.hinet.net','nngs.cosmic.org','aurora.go.art.pl']
  DEFS['Server']='igs.joyjoy.net'
  DEFS['Ports']= ['6969','9696','6969','9696']
  DEFS['Port']= '6969'
 # optional port: 7777
 # IP address:
 # 210.155.158.200
 # other servers:
 # lgs.hinet.net 9696
 # nngs.cosmic.org 6969
 # aurora.go.art.pl 9696

  DEFS['User'] = 'guest'
  DEFS['Password'] = ''
  DEFS['WoodBoard']= TkPhotoImage.new('file'=>$current_path+'../images/Vwood.gif')
  DEFS['white']= TkPhotoImage.new('file'=>$current_path+'../images/marb009.gif')
  DEFS['black']= TkPhotoImage.new('file'=>$current_path+'../images/marb039.gif')
  DEFS['gowin-bg']= DEFS['black']
  DEFS['goreplay-bg']= DEFS['black']
  DEFS['scrollwidth']= 150 # width of the slider in points
  DEFS['scrollwidth.max']= 350 #max moves for the slider

  DEFS['auto_start_Players']= true
  DEFS['auto_start_Games']= true
  DEFS['auto_start_Chat']= true
  DEFS['auto_raise_Chat']= false
  DEFS['auto_start_Reviews']= true
  DEFS['auto_start_Wlist']= true

  DEFS['show_help_balloons']=false
  DEFS['balloon_timein']=500 # ms
  DEFS['balloon_timeout']=3000 # ms

  DEFS['connection_timeout']= 15 # 15 minutes IGS timeout is 20mn
  DEFS['connection_keep_alive']= false # useful for wallpaper
# DEFS['WallPaper.geometry']='1024x768+0+0'  define your own preference

  DEFS['play_sounds']=false
  DEFS['sound_device']='/dev/dsp'

  DEFS['language']='C'

  DEFS['IGSList_background']= TkPhotoImage.new('file'=>$current_path+'../images/marb009.gif')
  DEFS['IGSList_title_background']= TkPhotoImage.new('file'=>$current_path+'../images/marb039.gif')
  DEFS['IGSList_title_foreground']= 'white'

  DEFS['players_cmd_country'] = ''
  DEFS['players_cmd_rank1'] = '8d'
  DEFS['players_cmd_rank2'] = '30k'
  DEFS['players_sort_type'] = 'all'


  DEFS['heads_directory']= $current_path+'../images/heads/'

  DEFS['CommonBackground']= TkPhotoImage.new('file'=>$current_path+'../images/lblue019.gif')
  DEFS['DeepBlue']= TkPhotoImage.new('file'=>$current_path+'../images/bleu2.gif')

  DEFS['ReplyText']= 'Sorry but I am not at my computer now'
  DEFS['talk_observing']= 'kibitz' # 'kibitz' is recorded in the sgf file on the server 'chatter' does not exist on nngs
# DEFS['tell_playing']= true

  DEFS['GoSimple.draw_woodboard']= false 
  DEFS['Goban.draw_woodboard']= true 
  DEFS['GoGame.draw_woodboard']= true
  DEFS['GobanSc.draw_woodboard']= true 

  DEFS['match_message']= 'Hello, would you like a game?'
  DEFS['VirtualText.clear']= 5 # auto_scroll in seconds
  DEFS['detached_comments']= true


  DEFS['last_move_mark']= 'Dame'
#other choices: Circle Rectangle Triangle

 # for sgf 'FG' property
  DEFS['show_coordinates']= true
  DEFS['show_hoshis']= true
  DEFS['list_moves_not_shown']= false
  DEFS['remove_captured_stones']= true
  DEFS['show_diagram_name']= true
  DEFS['remove_captured_stones']= true
  DEFS['list_hidden_moves']= true

 #defaults for sgf
  DEFS['game_time']= '1'
  DEFS['game_byo-yomi']= '10'
  DEFS['game_size']= '19'
  DEFS['game_color']= 'W'
  DEFS['marks_outline']= 'green'
  DEFS['marks_fill']= 'black'
  DEFS['marks_width']= 1.5
  DEFS['vars_color']= 'yellow'
  DEFS['show_siblings']= true
  DEFS['show_markup']= true
  DEFS['show_move_nb']= '0'

  DEFS['stipple']= 'gray25'
  DEFS['stipple-color']= 'black'
  DEFS['close_enough']= 4


  DEFS['show_players']= true
  DEFS['show_commands']= true
  DEFS['show_comments']= true


  DEFS['show_new_users']= false
  DEFS['show_closed_users']= true
  DEFS['show_playing_users']= true
  DEFS['open_for_match']= true
  DEFS['looking_for_match']= false
  DEFS['receive_shouts']=false
  DEFS['quiet']=false
  DEFS['multiple']=false


  DEFS['GoReplay_geom']= '600x600+100+100'
  DEFS['GoProbs_geom']= '600x600+100+100'
  DEFS['GoEditor_geom']= '600x600+100+100'
  DEFS['GoObserver_geom']= '600x600+100+100'
  DEFS['GoPlayer_geom']= '600x600+100+100'
  DEFS['GoTeacher_geom']= '600x600+100+100'
  DEFS['Reviewer_geom']= '600x600+100+100'
  DEFS['GnuGo_geom']= '600x600+100+100'
  DEFS['go_geom']= '+0+0'
  DEFS['GoClient_geom']= '+100+100'
  DEFS['Chat_geom']= '+100+100'
  DEFS['GoMatch_geom']= '+100+100'
  DEFS['Console_geom']= '600x500+200+200'
  DEFS['Players_geom']= '+400+0'
  DEFS['Reviews_geom']= '+300+0'
  DEFS['Wlist_geom']= '+500+0'
  DEFS['Games_geom']= '+400+400'
  DEFS['GoSetup_geom']= '600x600+100+100'
  DEFS['GoScore_geom']= '300x300+0+0'
  DEFS['Stats_geom']= '+200+200'
  DEFS['new_goban_geom']= '+200+200'
  DEFS['sgf_info_geom']= '+200+200'
  DEFS['browser_geom']= '+100+200'
  DEFS['icon_browser_geom']= '+200+200'
  DEFS['DiagramPrinter_geom']= '+200+200'
  DEFS['get_text_geom']= '+200+50'
  DEFS['get_double_geom']= '+200+50'
  DEFS['detached_geom']= '600x200+50+400'
  DEFS['TkHtml_geom']= '+200+0'
  DEFS['info_geom']= '+200+200'
  DEFS['message_geom']= '+200+200'
  DEFS['ViewSgf_geom']= '+200+200'
  DEFS['gg_new_game_geom']= '+200+200'
  DEFS['gg_new_game_size']= '19'
  DEFS['gg_new_game_komi']= '5.5'
  DEFS['gg_new_game_handi']= '0'
  DEFS['gg_new_game_level']= '10'
  DEFS['gg_show_beginner_help']= false

 #printing options

  if  $platform == 'windows'
    if File::SEPARATOR == '\\'
      DEFS['print_pathname']= 'C:\Temp\diagram.tex'
      DEFS['print_cmd']= '"C:\Program Files\Ghostgum\gsview\gsview32.exe" /p'
      DEFS['gv_prg']= '"C:\Program Files\Ghostgum\gsview\gsview32.exe"'
      DEFS['xdvi_prg']= 'C:\texmf\miktex\bin\yap.exe'
      DEFS['dvips_prg']='C:\texmf\miktex\bin\dvips.exe'
      DEFS['latex_prg']='C:\texmf\miktex\bin\latex.exe'
    else
      DEFS['print_pathname']= 'C:/Temp/diagram.tex'
      DEFS['print_cmd']= '"C:/Program Files/Ghostgum/gsview/gsview32.exe" /p'
      DEFS['gv_prg']= '"C:/Program Files/Ghostgum/gsview/gsview32.exe"'
      DEFS['xdvi_prg']= 'C:/texmf/miktex/bin/yap.exe'
      DEFS['dvips_prg']='C:/texmf/miktex/bin/dvips.exe'
      DEFS['latex_prg']='C:/texmf/miktex/bin/latex.exe'

    end
  else

    DEFS['print_pathname']= '/tmp/diagram.tex'
    DEFS['latex_prg']= 'latex'
    DEFS['xdvi_prg']= 'xdvi'
    DEFS['dvips_prg']= 'dvips'
    DEFS['print_cmd']= 'lpr'
    DEFS['gv_prg']= 'gv'

  end

  DEFS['make_dvi']= true
  DEFS['view_dvi']= true
  DEFS['make_ps']= false
  DEFS['view_ps']=false
  DEFS['print_ps']=false
  DEFS['print_color']= 'color'
  DEFS['print_paper']= 'a4paper'
  DEFS['print_diagram_width']= ''
  DEFS['print_float_figures']= true

 #Gnu Go options
  if  $platform == 'windows'
    DEFS['gnugo_cmd']= 'C:/gnugo/gnugo.exe'
  else
    DEFS['gnugo_cmd']= 'gnugo'
  end

  DEFS['gg_player_white']= 'Human'
  DEFS['gg_player_black']= 'Human'

  ICONS= Hash.new
  ICONS['no_match']= TkPhotoImage.new('file'=>$current_path+'../images/icons/closed.gif')
  ICONS['looking']= TkPhotoImage.new('file'=>$current_path+'../images/icons/looking.gif')
  ICONS['unknown']= TkPhotoImage.new('file'=>$current_path+'../images/icons/unknown.gif')
  ICONS['update']= TkPhotoImage.new('file'=>$current_path+'../images/icons/update.gif')
  ICONS['ready']= TkPhotoImage.new('file'=>$current_path+'../images/icons/ready.gif')



   #ICONS['reload']= TkPhotoImage.new('file'=>$current_path+'../images/icons/reload22.gif')
   #ICONS['quiet']= TkPhotoImage.new('file'=>$current_path+'../images/icons/quiet.gif')
  ICONS['tournament']= TkPhotoImage.new('file'=>$current_path+'../images/icons/tournament.gif')
  ICONS['teach']= TkPhotoImage.new('file'=>$current_path+'../images/icons/teach.gif')
  ICONS['free']= TkPhotoImage.new('file'=>$current_path+'../images/icons/ok.gif')
  ICONS['logout']= TkPhotoImage.new('file'=>$current_path+'../images/icons/logout.gif')

  ICONS['uncheck']= TkPhotoImage.new('file'=>$current_path+'../images/icons/unchecked.gif')
  ICONS['check']= TkPhotoImage.new('file'=>$current_path+'../images/icons/checked.gif')


  HEADS= Hash.new
  Dir.foreach(DEFS['heads_directory']) { |file|
    if file =~ /.*\.gif$/
      HEADS[file]= TkPhotoImage.new('file'=>DEFS['heads_directory']+file)
    end
  }

  REPLAY= Hash.new
  REPLAY['fast_forward']= 10 # number of moves
  REPLAY['fast_backward']= 10 
  REPLAY['play_interval']= 1.0 # in seconds
  REPLAY['play_fast_interval']= 0.1


  DEFS['stones_path']=$current_path+'../images/stones/'


  BStones= Array.new(60)
  WStones=Array.new(60)

  Dir.foreach(DEFS['stones_path']) { |name| 
    if name =~ /^white_(\d+).gif/
      WStones[$1.to_i]= TkPhotoImage.new('file'=>DEFS['stones_path']+name) if $1.to_i <= 60
    elsif name =~ /^black_(\d+).gif/
      BStones[$1.to_i]= TkPhotoImage.new('file'=>DEFS['stones_path']+name) if $1.to_i <= 60
    end
  }

  DEFS['sounds_path']= $current_path+'../sounds/'
  SOUNDS=Hash.new
  Dir.foreach( DEFS['sounds_path']) { |name| 
    if name =~ /.wav$/i

      buf= File.open(DEFS['sounds_path']+name) {|f| f.binmode; f.read }
      if $platform == 'linux'
        SOUNDS[name]= buf[44..-1]
      elsif $platform =='windows'
        SOUNDS[name]=buf
      end
    end
  }

  if ENV['RUBYGO_USER_FILES']
    $home= ENV['RUBYGO_USER_FILES'] 
  elsif  ENV['USERPROFILE']
    $home= File.join(ENV['USERPROFILE'],'RUBYGO_USER_FILES')
  elsif ENV['HOME']
    if $platform == 'windows'
      $home=ENV['HOME']+'RUBYGO_USER_FILES'
    else
      $home= File.join(ENV['HOME'],'.rubygo')
    end
  else
    $home='C:\RUBYGO_USER_FILES'
  end

  unless test(?r,$home)
    Misc.warning("directory #{$home} not found
I will create one to store your settings.")
    Dir.mkdir($home)
  end

  if $home
    puts 'user files in '+$home
  else
    $stderr.puts 'could not find a good place for user files'
    $home=$current_path
    $stderr.puts "using current path instead #{$current_path}"
  end

  ENTRY= Hash.new
  ENTVAL= Hash.new
  NOTES= Hash.new

  BOOKMARKS=["http://www.gobase.org/studying/analysed/",
      "http://senseis.xmp.net/?path=HikaruNoGoProblems&page=HikaruProblem1",
      "http://www.gobase.org/studying/gallery/?id=clear",
      "http://myhome.naver.com/dajava/lifedeath/hyunhyun/hyunhyun.html"]



  def Defaults.get_default_value(label)

#puts "Defaults:305"
    if ENTRY[label].nil?
      DEFS[label]= '1' if  DEFS[label]== 1 or  DEFS[label]== true
      DEFS[label]= '0' if  DEFS[label]== 0 or  DEFS[label] == false
  #  debug DEFS[label].gsub('\\\\','\\\\\\\\')
	if DEFS.key?(label)
	if DEFS[label].class == String
      ENTRY[label]=TkVariable.new(DEFS[label].gsub(/\\\\/,'\\\\\\\\'))
	else
		ENTRY[label]=TkVariable.new(DEFS[label])
	end
	else
    	debug "#{label}: #{ENTRY[label]}" 
	end
    end
    ENTRY[label]
  end

  def Defaults.set_default_value (label, value)
    if ENTRY[label].nil?
      ENTRY[label] = TkVariable.new(value) 
    else
      ENTRY[label].value= value
    end
  #  debug "#{label}: #{ENTRY[label]}" 
  end

  def Defaults.save_entry

    if test(?w, $home)
      file=  File.join($home,'ENTRY.rb')
    else
      $stderr.puts "could not open #{$home}, using #$current_path"
      file=  File.join($current_path , 'ENTRY.rb')
    end
    puts "\nsaving entries in #{file}"

    File.open(file,'w') { |f|
      f.puts '# File generated automatically - Do not edit - use '+File.join($home,'Defaults.rb')+' instead.'
      f.puts "module Defaults"
      ENTRY.each  { |key,tkvar| f.puts "ENTVAL['#{key}'] = '#{tkvar.value}'" }
      f.print "\nBOOKMARKS.clear\n"
      if BOOKMARKS.length > 0
        f.print "\nBOOKMARKS.push("
        for i in 0...BOOKMARKS.length
          f.print "'#{BOOKMARKS[i]}'"
          f.print ",\n" if i < BOOKMARKS.length - 1	
        end
        f.puts ")\n"
      end
      NOTES.each { |key,hash| f.puts "NOTES['#{key}'] = #{hash.inspect}" }
      f.puts "end"
      f.print '$defaultFiles='
      f.puts $defaultFiles.inspect
    }
  end


  def Defaults.load_entry

    if test(?w, $home)
      user_entry =  File.join($home,'ENTRY.rb')
    else
      puts "user entries not found"
      $defaultFiles={'defaultextension'=>'.sgf','filetypes'=> [['SGF File', '.sgf'],['MGT File', '.mgt']]}
      return
    end

    if test(?r,user_entry)
 # puts "found: #{user_entry}"
      load user_entry
      ENTVAL.each  { |key,var|  ENTRY[key]=TkVariable.new(var.gsub(/\\\\/,'\\\\\\\\'))}
      puts "user entries loaded"
    else
      puts "user entries not found"
    end

    $defaultFiles={'defaultextension'=>'.sgf','filetypes'=> [['SGF File', '.sgf'],['MGT File', '.mgt']]} unless $defaultFiles
  end


# make the clock blink when the player have less than 10s / move
  def Defaults.clock_alarm (clock,byo_stones)

    return if byo_stones <= 0


    tags = nil
    if clock/byo_stones <  10
      if clock < 60
        if  clock % 2 == 0
          tags= {'background' => 'red','foreground'=>'black'}
        end
      else
        tags= {'background' => 'orange','foreground'=>'black'}
      end

    elsif clock/byo_stones <  15
      tags= {'background' => 'yellow','foreground'=>'black'}
    end


    tags
  end


# filter the games displayed by wallpaper

  def Defaults.show_game(regmatch)
    regmatch[3].include?(?d) and regmatch[5].include?(?d)
  end


  # make the color tags for the console

  def Defaults.config_console_tags(w)
    w.tag_configure('user_cmd','foreground','cyan')
    w.tag_configure('error','foreground','red')
    w.tag_configure('tell', 'foreground','yellow')
    w.tag_configure('say','foreground','orange')
    w.tag_configure('kibitz','foreground','white')
    w.tag_configure('info','foreground','green')
    w.tag_configure('normal','foreground','white')
    w.tag_configure('shout','foreground','pink')
  end

   # filtered output of the console
   # return a tag defined above or false

  def Defaults.console_show(code,line)

    case code

    when IGSProtocol::BEEP
    when IGSProtocol::MOVE
    when IGSProtocol::STATUS
    when IGSProtocol::KIBITZ
    when IGSProtocol::SAY
    when IGSProtocol::IGS
    when IGSProtocol::USER
    when IGSProtocol::GAMES
    when IGSProtocol::AUTOASK
      return 'info'
    when IGSProtocol::PROMPT
    when IGSProtocol::SHOUT
      return 'shout' unless line[0] == ?{
    when IGSProtocol::TELL
	  if line =~ /SYSTEM/
		return 'tell'
		else
      return false
	end
    when IGSProtocol::INFO
      return false if line =~ /^Game is titled/
      return false if line == 'File'
      return 'info' unless $statobserver.buffer 
    when IGSProtocol::ERROR
      return 'error'
    else
      return 'normal'
    end

 #      return false
  end


   # don't show guest players in the list
   # def Defaults.show_player(user)
   #  return  (not user.name[0..4] == 'guest')
   #end

 # returns the time interval between two moves in GoReplay

    @time_interval= REPLAY['play_interval']

    def Defaults.time_interval
      (@time_interval*1000).to_i
    end

 # function called by the ">|" and ">>" buttons in the GoReplay interface

    def Defaults.set_time_interval(which)
      case which 
      when 'normal'
        @time_interval= REPLAY['play_interval']
      when 'fast'
        @time_interval= REPLAY['play_fast_interval']
      end
    end

    def Defaults.open_url(url)

      case $platform 
      when "windows"
     #alternative:     
#system("#{ENV["COMSPEC"]} /c  start #{url}" )
        require 'win32ole'
        ie = WIN32OLE.new('InternetExplorer.Application')
        ie.visible = true
        ie.navigate( url)
      when  "linux"
    # try to determine the desktop (basic :->)
        unless browser= ENV['BROWSER']
          plist= `ps -u #{ENV['USER']}`
          if plist.include?('kde')
            browser='konqueror'
          elsif  plist.include?('gnome')
            browser='galeon'
          else
            browser = 'mozilla'
          end
        end
        case browser
        when 'konqueror'
          system("kfmclient openURL #{url}&")
        when 'galeon'
          system("galeon -x  #{url}&")
        when 'mozilla'
       # system("netscape -remote 'openURL(#{url})'" 
          system("mozilla #{url}&")
        end
      when "sun"
     #must have one netscape running on the same display
        system("netscape -remote 'openURL(#{url})'" )
      end
    end


  end # module Defaults


  module PlayersMenu

    def menu_init
      @menu = Menu.new
      @menu.configure('tearoff'=>'false')
      @menu.add('command', 'font'=>'fixed', 'label' => 'Player', 'state'=>'disabled')
      @menu.add('separator')
      @menu.add('command', 'font'=>'fixed', 'label' => 'stats', 'command' => proc { send_stats } )
      @menu.add('command', 'font'=>'fixed', 'label' => 'chat', 'command' => proc { open_chat } )
      @menu.add('command', 'font'=>'fixed', 'label' => 'results', 'command' => proc { send_results } )
      @menu.add('command', 'font'=>'fixed', 'label' => 'observe', 'command' => proc { send_observe } )
      @menu.add('command', 'font'=>'fixed', 'label' => 'match', 'command' => proc { send_match } )
      @menu.add('command', 'font'=>'fixed', 'label' => 'automatch', 'command' => proc { send_automatch } )

    end

    def popup( x_root,y_root,userinfo )
      @userinfo= userinfo 
      @menu.entryconfigure(0,'label'=>userinfo.name)
      if  @userinfo.playing
        @menu.entryconfigure(5,'state'=>'normal','label'=>'observe '+ @userinfo.playing)
      elsif  @userinfo.observing
        @menu.entryconfigure(5,'state'=>'normal','label'=>'observe '+ @userinfo.observing)
      else
        @menu.entryconfigure(5,'state'=>'disabled')
      end
      @menu.post( x_root, y_root)
    end

    def send_stats
      $igsClient.send('stats '+ @userinfo.name)
    end

    def send_results
      $igsClient.send('results '+ @userinfo.name)
    end

    def send_observe
      if  @userinfo.playing
        $igsClient.send('observe '+  @userinfo.playing)
      elsif  @userinfo.observing
        $igsClient.send('observe '+ @userinfo.observing)
      end
    end

    def send_match
      GoMatch.new('match '+ @userinfo.name,@userinfo.name)
    end

    def send_automatch
      $igsClient.send('automatch '+ @userinfo.name)
    end

    def open_chat
      $chatobserver.new_chat(@userinfo.name) unless $chatobserver.nil?
    end

  end # module

  module GamesMenu

    def menu_init
      @menu = Menu.new
      @menu.configure('tearoff'=>'false')
      @menu.add('command', 'font'=> $fixed_font, 'state'=>'disabled')
      @menu.add('separator')
      @menu.add('command', 'font'=> $fixed_font)
      @menu.add('command', 'font'=> $fixed_font)
      @menu.add('command', 'font'=> $fixed_font)
      @menu.add('command', 'font'=> $fixed_font)
    end

    def popup(x_root,y_root,gameinfo )
      @gameinfo= gameinfo 
      @menu.entryconfigure(0,'label'=>'Game '+ gameinfo.number.to_s)
      @menu.entryconfigure(2, 'label' => 'observe', 'command' => proc { send_observe(@gameinfo.number.to_s) } )
      @menu.entryconfigure(3,'label' => 'stats '+gameinfo.w_player , 'command' => proc { send_stats(@gameinfo.w_player)})
      @menu.entryconfigure(4,'label' => 'stats '+gameinfo.b_player , 'command' => proc { send_stats(@gameinfo.b_player) })
      @menu.entryconfigure(5, 'label' => 'wallpaper', 'command' => proc { observe_as_wallpaper(@gameinfo.number.to_s) } ) if  Object.const_defined?(:WallPaper)
      @menu.post( x_root, y_root)
    end

    def   observe_as_wallpaper(nb)
      $wallpaper_game = nb.to_i
      send_observe(nb)
    end

    def send_observe(nb)
      $igsClient.send('observe '+ nb)
    end

    def send_stats(pl)
      $igsClient.send('stats '+ pl)
    end


  end # module


  user_defs=File.join($home,'Defaults.rb')
  if test(?r,user_defs)
    load user_defs
    puts "user defaults loaded"
  else
    puts "user defaults not found"
  end

  Defaults.load_entry
