

module DiagramPrinter

  Print_DefaultFiles={'defaultextension'=>'.tex','filetypes'=> [['Latex source', '.tex']]}


  def print_diagram

    open_options
  end


  def open_options

    @print_buffer="
\\documentclass[#@print_paper]{article}
\\usepackage{graphicx}
\\usepackage[T1]{fontenc}
\\usepackage[latin1]{inputenc}
\\begin{document}
\\renewcommand{\\figurename}{Dia.}
    "

    @print_index=0

    @print_form= Form.new('DiagramPrinter')
    frame=@print_form.add_frame('DiagramPrinter.frame.print',0,0)
    @print_form.add_label(frame,'DiagramPrinter.label.file',0,0)

    @print_pathname=Defaults.get_default_value('print_pathname')
    @print_fullname= @print_pathname.value
    @print_dirname=File.dirname(@print_fullname)

    @print_filename= File.basename(@print_fullname,'.tex')

    Print_DefaultFiles.update('initialfile'=> @print_filename+ '.tex','initialdir'=> @print_dirname)

    bt= TkButton.new(frame,'text'=>@print_filename+ '.tex','command'=> proc { choose_file(bt) })
    @print_form.add(bt,1,0)

    @print_form.add_label(frame,'DiagramPrinter.label.mode',0,1)
    @print_color_mode=Defaults.get_default_value('print_color')
    @print_form.add_radio(frame,@print_color_mode,1,1,'color','mono')

    @print_paper= Defaults.get_default_value('print_paper')
    @print_form.add_label(frame,'DiagramPrinter.label.paper',0,2)
    @print_form.add_menu(frame,@print_paper,1,2,'a4paper','letter')

    @print_form.add_label(frame,'DiagramPrinter.label.diagram width',0,3)
    @print_diagram_width= Defaults.get_default_value('print_diagram_width')
    @print_form.add_field(frame,'DiagramPrinter.entry.diagram width',@print_diagram_width,'normal',1,3)
    @print_form.add_check(frame,'DiagramPrinter.button.float figures',@print_float_figures,1,4)

    frame=@print_form.add_frame('DiagramPrinter.frame.print',1,0)

    @print_form.add_label(frame,'DiagramPrinter.label.latex program',0,0)
    @latex_prg= Defaults.get_default_value('latex_prg')
    @print_form.add_field(frame,'DiagramPrinter.entry.latex program',@latex_prg,'normal',1,0)

    @print_form.add_label(frame,'DiagramPrinter.label.DVI viewer',0,1)
    @xdvi_prg= Defaults.get_default_value('xdvi_prg')
    @print_form.add_field(frame,'DiagramPrinter.entry.DVI viewer',@xdvi_prg,'normal',1,1)

    @print_form.add_label(frame,'DiagramPrinter.label.make Postscript with',0,2)
    @dvips_prg= Defaults.get_default_value('dvips_prg')
    @print_form.add_field(frame,'DiagramPrinter.entry.make Postscript with',@dvips_prg,'normal',1,2)

    @print_form.add_label(frame,'DiagramPrinter.label.view Postscript with',0,3)
    @gv_prg= Defaults.get_default_value('gv_prg')
    @print_form.add_field(frame,'DiagramPrinter.entry.view Postscript with',@gv_prg,'normal',1,3)

    @print_form.add_label(frame,'DiagramPrinter.label.print command',0,4)
    @print_cmd= Defaults.get_default_value('print_cmd')
    @print_form.add_field(frame,'DiagramPrinter.entry.print command',@print_cmd,'normal',1,4)

    frame=@print_form.add_frame('DiagramPrinter.frame.print',1,1)

    @make_dvi= Defaults.get_default_value('make_dvi')
    b=@print_form.add_check(frame,'DiagramPrinter.button.make DVI',@make_dvi,0,0)
    b.configure('command'=> proc {
      if @make_dvi.value == '0'
                @view_dvi.value= '0'
                @make_ps.value= '0'
                @view_ps.value = '0'
                @print_ps.value= '0'
      end
    })

    @view_dvi= Defaults.get_default_value('view_dvi')
    b=@print_form.add_check(frame,'DiagramPrinter.button.view DVI',@view_dvi,0,1)
    b.configure('command'=> proc { @make_dvi.value= '1' if @view_dvi.value == '1'})

    @make_ps= Defaults.get_default_value('make_ps')
    b=@print_form.add_check(frame,'DiagramPrinter.button.make Postscript',@make_ps,1,0)
    b.configure('command'=> proc {
      if  @make_ps.value== '0'
                @view_ps.value = '0'
                @print_ps.value= '0'
      else
        @make_dvi.value= '1'
      end })


    @view_ps= Defaults.get_default_value('view_ps')
    b=@print_form.add_check(frame,'DiagramPrinter.button.view Postscript',@view_ps,1,1)
    b.configure('command'=> proc { @make_ps.value= '1' if @view_ps.value == '1'})

    @print_ps= Defaults.get_default_value('print_ps')
    b=@print_form.add_check(frame,'DiagramPrinter.button.print Postscript',@print_ps,1,2)
    b.configure('command'=> proc { @make_ps.value= '1' if @print_ps.value == '1'})

    frame= @print_form.add_frame('GoReplay.frame.sgf_info',0,1)
    frame.grid('ipadx'=>0, 'ipady'=>0)

    opts=TkDefaults::GUI['DiagramPrinter.button.add'].update('command'=> proc { add_to_buffer })
    TkButton.new(frame,opts).pack('side'=>'left')

    opts=TkDefaults::GUI['DiagramPrinter.button.make'].update('command'=> proc { do_script; @print_form.destroy})
    TkButton.new(frame,opts).pack('side'=>'left')

    opts=TkDefaults::GUI['DiagramPrinter.button.close'].update( 'command'=> proc { @print_form.destroy})
    TkButton.new(frame,opts).pack('side'=>'left')

  end

  def choose_file(bt)

    file=@print_form.getSaveFile(Print_DefaultFiles)

    return if file.empty?

    @print_dirname=File.dirname(file)
    @print_filename= File.basename(file,'.tex')
    @print_fullname= File.join( @print_dirname, @print_filename+ '.tex')
    @print_pathname.value= @print_fullname

    Print_DefaultFiles.update('initialfile'=> @print_filename,'initialdir'=> @print_dirname)

    bt.configure('text'=>@print_filename+'.tex')
  end

  def add_to_buffer

    diagram_list=  get_goban

  #TODO include personal file

  #   capname= @current_node['N'].values[0]
    caption=""
    diagram_name= ""


    if @show_diagram_name == '1'
      if  @current_node['N'].nil?
        caption="\\caption{}\n"
      else
        diagram_name= @current_node['N'].values[0]
        caption="\\caption{#{diagram_name}}"
      end
    end

    buffer="\n\\begin{center}"

    diagram_list.each { |fig| buffer <<  fig }


    if @show_list_moves.value== '1' and not @list_hidden_moves.empty?
      buffer << "
 \\textsl{\\small{\\\\"

#[st.color,st.col,st.row,st.nb]

      @list_hidden_moves.each { |p|
        coords=Grid.to_coords(p[1], p[2], @height)
        buffer << "#{p[3]}: #{coords} " }

      buffer << "}}\n"
    end

    buffer << "\n\\end{center}"


    if @print_float_figures.value== '1'
      buffer= "\n\\begin{figure}[hptb]" << buffer
      buffer<<"\n#{caption}" unless caption.empty?
#buffer << "\n\\label{dia:#@print_index}"
      buffer << "\n\\end{figure}"
  end

  text= @talk.get_text
  unless text.empty?
    buffer << "\n\\paragraph{Diagram #@print_index: #{diagram_name}}\n"

#TODO: handle specila chars

    text.gsub!('\#','\#')
    text.gsub!('\$','\$')
    text.gsub!('\%','\%')
    text.gsub!('\~','') # problem
    text.gsub!('\&','')
    text.gsub!('\^','') # problem
    text.gsub!('\_','\_')

    buffer << text

  end

  @print_buffer << buffer
  end

  def make_tex
    if @print_index ==0
      Misc::warning('You need to add figures to the list before produce an output')
      return
    end
    if @print_filename.empty?
      Misc::warning('Missing filename for output')
      return
    end
    @print_buffer << "\n\\end{document}"

    File.open(@print_fullname, "w+") { |f| f.puts(@print_buffer) }

  end

  def do_script

    if @make_dvi == '0'
      Misc.warning( "You should at least produce the DVI file") if $? != 0
      return
    end

    make_tex

#system(['/usr/bin/latex','latex'],@print_fullname )

    old_dir=Dir.pwd

    name = File.join(@print_dirname,@print_filename)
    log "changing dir to #@print_dirname"
    Dir.chdir(@print_dirname)
    do_system ("#@latex_prg #@print_filename.tex") if @make_dvi.value == '1' and not @latex_prg.value.empty?
    return if $system_return_code != 0
    do_system( "#@xdvi_prg #@print_filename.dvi" ) if @view_dvi.value == '1' and not @xdvi_prg.value.empty?
    do_system( "#@dvips_prg  #@print_filename.dvi -o #@print_filename.ps") if @make_ps.value == '1' and not @dvips_prg.value.empty?

    return if $system_return_code != 0
    do_system( "#@gv_prg #@print_filename.ps" ) if @view_ps.value == '1' and not @gv_prg.value.empty?
    do_system("#@print_cmd #@print_filename.ps" ) if @print_ps == '1' and not @print_cmd.value.empty?

    Dir.chdir(old_dir)
  end


  def do_system(args)
    system(args)
    str= args
    log("running command: #{str}")
    Misc.warning( "Error executing\n #{str}") if $system_return_code != 0
  end

  def log(str)
    $stdout.puts("=> "+str)
  end

  def get_goban
    print_diagram_list= []
    full_board=true
    @goban.items.each{ |item| full_board= false if item.class == View }

    if full_board
      x=y=0
      height= @goban.grid.height- @goban.grid.marge
      width= @goban.grid.width- @goban.grid.marge
      file= File.join(@print_dirname,@print_filename + '.eps')

      goban.postscript('file'=>File.join(@print_dirname,@print_filename+ @print_index.to_s + '.eps'),
                       'x'=>x,'y'=>y,'width'=>width,'height'=>height,
                       'colormode'=>@print_color_mode.value)

      if @print_diagram_width.value.empty?
        if width >= height
          diagram_size= 'width=\textwidth'
        else
          diagram_size= 'height=\textwidth'
        end
      else
        diagram_size= "width=#{@print_diagram_width.value}\\textwidth"
      end
      print_diagram_list.push("\n\\includegraphics[#{diagram_size}]{#@print_filename#{@print_index}.eps}")
      @print_index+=1

    else

      x=y=width=height=0

      @goban.items.each { |item|
        if item.class == View
          x= item.a1+1
          y=item.b1+1
          width= item.a2-item.a1-2
          height= item.b2-item.b1-2

          if @print_diagram_width.value.empty?
            minipage_size= "0.5\\textwidth"
          else
            minipage_size= "#{@print_diagram_width.value}\\textwidth"
          end

          if width >= height
            diagram_size= 'width=\textwidth'
          else
            diagram_size= 'height=\textwidth'
          end

          file= File.join(@print_dirname,@print_filename +@print_index.to_s+ '.eps')

          goban.postscript('file'=>file,
                           'x'=>x,'y'=>y,'width'=>width,'height'=>height,
                           'colormode'=>@print_color_mode.value)


          print_diagram_list.push("
\\begin{minipage}{#{minipage_size}}
\\includegraphics[#{diagram_size}]{#@print_filename#{@print_index}.eps}
\\end{minipage}" )

          @print_index+=1
        end
      }

    end

    return  print_diagram_list

  end

  def save_bw_diagram

    diagr = GoWindow.new(self)
    gb=GoSimple.new(diagr,@width,@height).pack('fill'=> 'both','expand'=>'yes')
    copy_goban(gb)

    TkButton.new(diagr,'text'=>'Save','command'=> proc {

                 height= gb.grid.height- gb.grid.marge
                 width= gb.grid.width- gb.grid.marge
                 gb.postscript('file'=>'/tmp/diagr.eps',
                               'x'=>0,'y'=>0,'width'=>width,'height'=>height,
                               'colormode'=> 'mono')}).pack

  end

end


