#!/usr/local/bin/ruby
#  encoding: utf-8
#  d_new.rb
#
#  Created by midori on 2006-03-24.
#  Copyright (c) 2006. All rights reserved.
#  You can distribute/modify this program under the terms of the Ruby License.
#  Last change: 2006-10-25.
#______________________________________________________________ New Post
class NewPost
  
  include MakeXML
  include ReadWrite
  def initialize( myhash )
    require "time"
    h = Hash.new; t = Time.now
    youbi = ["日曜","月曜", "火曜", "水曜", "木曜", "金曜", "土曜"][t.wday]
    h['full'] = t; h['t_i'] = t.to_i; h['d_y'] = t.year; h['d_m'] = t.strftime("%m"); h['d_d'] = t.strftime("%d")
    h['t_h']=t.strftime("%H"); h['t_mm'] = t.strftime("%M"); h['t_sec'] = t.sec; h['d_w']=youbi
    h['postdate'] = [t.year,"/", t.strftime("%m"),"/",t.strftime("%d"),"(",youbi,") ", t.strftime("%H"),":",t.strftime("%M")].to_s
    @metadata = h
    
    @path_trash = myhash["trash"]
    @xml_dir = myhash["dir_xml"]
    @xhtml_dir = myhash["dir_xhtml"]
    @uri_archives_path = myhash["url_archives_path"]

    @path_xsl = myhash["f_xsl_post"]
    @path_log_xml = myhash["f_log_xml"]
    @path_lwws_dir = myhash["lwws_xmldir"]
    # 2006-10-25
    @path_new_xml = File.join(@xml_dir, @metadata['d_y'].to_s, @metadata['d_m'].to_s, [@metadata["t_i"], ".xml"].to_s)
    @path_new_html = File.join(@xhtml_dir, @metadata['d_y'].to_s, @metadata['d_m'].to_s, [@metadata["t_i"], ".html"].to_s)
    @uri_new_html = File.join(@uri_archives_path, @metadata['d_y'].to_s, @metadata['d_m'].to_s, [@metadata["t_i"].to_s,".html"].to_s)
    
  end
  def post_parent(para_data)
    require "fileutils"
    # XML
    new_xml = p_makexml_parent(para_data)
    check_xmldir = File.join(@xml_dir, @metadata['d_y'].to_s, @metadata['d_m'].to_s)
    FileUtils.mkdir_p(check_xmldir)
    m_write_file(@path_new_xml, new_xml)
    
    # LOG
    logdata = [ @metadata["full"].to_s, ",", @path_new_xml,"\n"]
    m_log_write_file(@path_log_xml, logdata)
    #Fri Oct 27 20:16:15 JST 2006,/xxx/xxx/daybook/daybook_xml/2006/10/1161947775.xml
    
    # XHTML
    new_xhtml = m_apply_xsl_path(new_xml, @path_xsl)
    check_htmldir = File.join(@xhtml_dir, @metadata['d_y'].to_s, @metadata['d_m'].to_s)
    
    FileUtils.mkdir_p(check_htmldir)
    m_write_file(@path_new_html, new_xhtml)
    #return new_xmlaa
    ok_mes = "<a href='#{@uri_new_html}'>NewPost Success</a>"
    return ok_mes
    
  end
  def post_child(para_data)
    require "fileutils"
    FileUtils.mkdir_p(@path_trash)
    # path
    path_env = ENV["HTTP_REFERER"].to_s
    xml_name = File.basename(path_env).gsub(".html", ".xml")
    html_name = File.basename(path_env)
    # XML Path
    path_xml = "path"
    unless xml_name.empty?
    m_common_count_xmlfiles(@path_log_xml).each{ |line|
       path_xml =  line if line =~ /#{xml_name}/
    }
    end
    
    return "Error, not found XML file" unless FileTest.exist?(path_xml)
    doc = m_read_xml(path_xml); str_xml = doc.to_s
    str_xml = p_makexml_child(path_xml, para_data)
    path_trash_xml = File.join(@path_trash, xml_name)
    # save xml
    p_save( path_xml, path_trash_xml, str_xml )
    
    # HTML path Get data XML Element
    d_y = doc.elements['entry/meta/metadate/d_y'].text
    d_m = doc.elements['entry/meta/metadate/d_m'].text
    t_i = doc.elements['entry/meta/metadate/t_i'].text
    path_html = File.join(@xhtml_dir, d_y, d_m, [t_i,".html"].to_s)
    
    return "Error, not found HTML file" unless FileTest.exist?(path_html)
    str_html = m_apply_xsl_path(str_xml, @path_xsl)
    path_trash_html = File.join(@path_trash, html_name)
    # save html
    p_save( path_html, path_trash_html, str_html )
    #  end of Message
    ok_mes = "<a href='#{path_html.gsub!( @xhtml_dir, @uri_archives_path)}'>Success</a>"
    return ok_mes
    
  end
  
  private
  def p_save(path, trash, str)
    File.rename(path, trash) if FileTest.exist?(path)
    m_write_file(path, str)
  end

  def p_comment_element(para_data, item)
    # <ore><code> Code Text of Comment
    para_data.each{|key ,value| m_add_my_element(item, "#{key}", "#{value}")}
    ele_comment = item.elements["comment"]
    list_words = para_data["comment"]
    flag = 0
    str_pre = "\n"
    list_words.each{|w| 
      case w
      # 2006-10-11
      # <<< code text >>> is pre element
      when /.*#62;.*#62;.*#62;$/ then
        unless ele_comment.elements['pre'].nil?
          ele_pre = ele_comment.get_elements('pre').last
          ele_pre.add_text(str_pre)
          flag = 0; str_pre = ""
        end
      when /.*#60;.*#60;.*#60;$/ then
          ele_pre = ele_comment.add_element("pre"); flag = 1
      else
        #------------------------
        if flag == 0
          # [[URL,URLtitle]] is Link element
          w.gsub!(/&amp;#91;(http.?&amp;#58;.*)&#44;(.*)&#93;/){"<a href='"+$1+ "'>" +$2 +"</a>"}
          ele_p = ele_comment.add_element("p")
            if w == "\n"
              ele_p.add_text("<br />")
            else
              ele_p.add_text(w.chomp)
            end
          ele_comment.add_text("\n")
        else
          str_pre << w
        end
        #------------------------
      end
         }
         
      if ele_comment.get_elements("p").empty?
        ele_p = ele_comment.add_element("p");ele_p.add_text(" ")
      end
      return item
  end
  def p_makexml_parent(para_data)
    doc = m_make_new_xml("entry")
    docroot = doc.root
    meta = docroot.add_element("meta")
    uri = m_add_my_element(meta, "uri",  @uri_new_html)  
    m_add_my_element(meta, "itemcount",  "0")
    m_add_my_element(meta, "itempostno", "0")
    
    metadate = m_add_my_element(meta, "metadate", "")
    @metadata.sort.each{ |key ,value|
      m_add_my_element(metadate, "#{key}", "#{value}")
    }    
    item = docroot.add_element("item")
    # LWWS
    m_add_my_element(item, "telop", p_get_weather)
    # postno
    m_add_my_element(item, "postno", "0")
    m_add_my_element(item, "date", @metadata["postdate"])
    # code format
    p_comment_element(para_data, item)
    
    metadate.add_text("\n"); meta.add_text("\n"); item.add_text("\n")
    docroot.add_text("\n"); docroot.add_text("\n")
    return doc.to_s
  end
  def p_makexml_child(path_xml, para_data)
    postdoc = m_read_xml(path_xml)
    docroot = postdoc.root
    # UPDATE [entry/meta/itemcount] COUNT UP
    itemcount = docroot.elements["meta/itemcount"].get_text.to_s.to_i; item_count = itemcount + 1
    itempotno = docroot.elements["meta/itempostno"].get_text.to_s.to_i; item_potno = itempotno + 1
    docroot.elements["meta/itemcount"].text = item_count.to_s
    docroot.elements["meta/itempostno"].text = item_potno.to_s
    
    item = docroot.add_element("item_comment")
    m_add_my_element(item, "date", @metadata["postdate"])
    m_add_my_element(item, "postno", item_potno.to_s)
    # format text
    p_comment_element(para_data, item)
    
    item.add_text("\n")
    docroot.add_text("\n")
    return postdoc.to_s
  end
  def p_get_weather
    # LWWS DATA
    path_today_name = [ @metadata['d_y'],"_",@metadata['d_m'], "_",@metadata['d_d'],".xml"].to_s
    path_today_xml = File.join( @path_lwws_dir, path_today_name)
    if FileTest.exist?(path_today_xml)
      doc = Document.new(File.new( path_today_xml ))
      telop = doc.root.elements["telop"].text
       return telop
    end
  end
end