#!/usr/local/bin/ruby
#  encoding: utf-8
#  d_search.rb
#
#  Created by midori on 2006-09-24.
#  Copyright (c) 2006. All rights reserved.
#  You can distribute/modify this program under the terms of the Ruby License.
#  Last change: 2006-10-23.

#______________________________________________________________ Search
class MySearch
  include MakeXML
  include ReadWrite
  def initialize(myhash)
    @path_xsl = myhash["f_xsl_search"]
    @path_log_xml = myhash["f_log_xml"]
    @list_element = ["entry/meta/itemcount", "entry/meta/uri", "/entry/meta/metadate/t_i/", "entry/item/subject", "entry/item/date", "entry/item/name"]
  end
  def mysearch_board_search(h_inputdata)
    search_str = h_inputdata['search']
    str_xml = p_search_xml_make(p_getlist, search_str)
    str_html = m_apply_xsl_path(str_xml, @path_xsl)
    return str_html
  end
  
  private
  def p_search_xml_make(p_getlist, search_str)
    e_search_str = Regexp.escape("#{search_str}")
    h = Hash.new{|h, key| h[key] = []}
    archivesdoc = m_make_new_xml("archives")
    docroot = archivesdoc.root
    meta = docroot.add_element("metadate")
    meta.add_text(Time.now.to_s)
    docroot.add_text("\n")
    entries = docroot.add_element("entries")
    #
    p_getlist.each{|f| 
     onefiledoc = Document.new(File.new( f ))
     t_i = onefiledoc.root.elements["meta/metadate/t_i"].text     
     parent_post = onefiledoc.root.elements["item"].to_s.gsub(/<.*?>/,"")
     parent_post << onefiledoc.root.get_elements('item_comment').to_s.gsub(/<.*?>/,"")
     
     if parent_post =~ /#{e_search_str}/ui
       entry = REXML::Element.new( "entry" )
       @list_element.each{|e| entry.add_element(onefiledoc.elements[e])}
       
       onefiledoc.root.get_elements('item_comment').each{|d| 
       target_str = d.to_s.gsub(/<.*?>/,"")
       if target_str =~ /#{e_search_str}/i
         ic = entry.add_element("item_comment")
         ic.add_element(d.elements["postno"])
         ic.add_element(d.elements["name"])
         ic.add_element(d.elements["comment/p"])
       end
        }
        h["#{t_i.to_s}"] << entry
     end
    }
    #
    h.sort.reverse.each{|key, value|
      value.each{|v| entries.add_element(v)}
      }
    entries.add_text("\n")
    docroot.add_text("\n")
    return archivesdoc.to_s
  end
  def p_getlist
    m_common_count_xmlfiles(@path_log_xml)
  end
end