#!/usr/local/bin/ruby
#  encoding: utf-8
#  d_remake.rb

#  Created by midori on 2006-10-25.
#  Copyright (c) 2006. All rights reserved.
#  You can distribute/modify this program under the terms of the Ruby License.
#  Last change: 2006-10-25.
#  2006-10-25 rss2
class HTMLRemake
  include CheckPath
  include MakeXML
  include ReadWrite
def initialize(myhash)
  @xml_dir = myhash["dir_xml"]
  @xhtml_dir = myhash["dir_xhtml"]
  @uri_archives_path = myhash["url_archives_path"]
  @path_trash = myhash["trash"]
  @path_xsl = myhash["f_xsl_post"]
  @path_log_xml = myhash["f_log_xml"]
  @path_rss =  File.join(myhash["dir_pub"], "daybook", "dRSS2.xml")
end
def rss2
  list_channel = {
    "title"=>"midore_daybook",
    "link"=>"http://www.midore.net/daybook/daybook_index.html",
    "description"=>"ruby, xml, xsl",
    "language"=>"ja",
    "copyright"=>"Copyright 2006, Midore"
      }
   list_item = { 'pubDate'=>"/entry/meta/metadate/full",'title'=> "entry/item/subject",
            'link'=> "entry/meta/uri",'description'=>"entry/item/comment/p",'guid'=>"entry/meta/uri"}
  
  list_targetxml = m_common_count_xmlfiles(@path_log_xml)
  require "time"
  doc = m_make_new_xml("rss");docroot = doc.root
  docroot.add_attribute("version", value="2.0");docroot.add_text("\n")
  channel = docroot.add_element("channel")

  list_channel.each{|key, value| 
    ele_key = channel.add_element(key)
    ele_key.add_text(value)
    }
    list_targetxml.each{|f|
      onefiledoc = Document.new(File.new( f ))
      channel.add_text("\n")
      item = channel.add_element("item")
      item.add_text("\n")
      list_item.each{|key, value|
         ele_key = item.add_element(key)
         case key
         when 'guid'
           ele_key.add_attribute(REXML::Attribute.new("isPermaLink", "true"))
           ele_key.add_text(onefiledoc.elements["#{value}"].text)
         when 'pubDate'
           u_rfctime = Time.parse(onefiledoc.elements["#{value}"].text).rfc822
           ele_key.add_text("#{u_rfctime}")
         when 'title'
           s_title = onefiledoc.elements["#{value}"].text
           us_title = s_title.gsub(/&#\d.*;/, " ")
           ele_key.add_text(us_title)
         else
             ele_key.add_text(onefiledoc.elements["#{value}"].text)
         end
         item.add_text("\n")
         }
      }
      
    channel.add_text("\n")
    # save xml
    path_trash_rss = File.join(@path_trash, "rss.xml")
    p_remakesave( @path_rss, path_trash_rss, doc.to_s )
    
    return "RSS Success"
end
def del_id(id)
  # xml path
  path_xml = p_get_xmlpath(id)
  # html path
  begin
    doc = m_read_xml(path_xml)
    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)
    path_trash_html = File.join(@path_trash, [id, ".html"].to_s)
    # html remove
    File.rename(path_html, path_trash_html) if FileTest.exist?(path_html)
    # xml remove
    path_trash_xml = File.join(@path_trash, [id, ".xml"].to_s)
    File.rename(path_xml, path_trash_xml) if FileTest.exist?(path_xml)
    # end of message
    return "Delete_File#{id} Success"
  rescue
    return "Error ,Somethig"
  end
  
end

def del_no(id, no)
  # xml path
  path_xml = p_get_xmlpath(id)
  # xml data
  doc = m_read_xml(path_xml)#; str_xml = doc.to_s
  comment_list =  doc.get_elements("entry/item_comment")
  comment_list.each{ |x|
    case x.elements["postno"].get_text
    when no.to_i then 
      # Delete Element of Post No
      doc.delete_element( x.xpath )
      # COUNTER UPDATE
      now_itemcnt = doc.elements["entry/meta/itemcount"].get_text.to_s.to_i
      cnt = now_itemcnt - 1
      doc.elements["entry/meta/itemcount"].text = cnt.to_s
      str_xml = doc.to_s
      # save xml
      path_trash_xml = File.join(@path_trash, [id, ".xml"].to_s)
      p_remakesave( path_xml, path_trash_xml, str_xml )
      # save html
      remake_onlyfile(id)
      # end of message
      return "Delete_PostNO.#{no} of #{id}, Success"
      
    end
  }
  
  return "Not Found Post No"
  
end

def remake_all
  require "fileutils"
  mylist = Array.new
  error_list = Array.new
  
  m_common_count_xmlfiles(@path_log_xml).each{|path_xml|
    begin
      # get data of xml file
      doc = m_read_xml(path_xml); str_xml = doc.to_s
      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
      fulldate = doc.elements['entry/meta/metadate/full'].text
      # save html
      FileUtils.mkdir_p(File.join(@xhtml_dir, d_y, d_m))
      path_html = File.join(@xhtml_dir, d_y, d_m, [t_i,".html"].to_s)
      str_html = m_apply_xsl_path(str_xml, @path_xsl)
      p_remakesave( path_html, File.join(@path_trash, "cash.txt"), str_html)
      # save xml
      FileUtils.mkdir_p(File.join(@xml_dir, d_y, d_m))
      path_newxml = File.join(@xml_dir, d_y, d_m, [t_i,".xml"].to_s)
      doc.elements['entry/meta/uri'].text = File.join(@uri_archives_path, d_y, d_m, [t_i,".html"].to_s).to_s
      str_newxml = doc.to_s
      p_remakesave(path_newxml, File.join(@path_trash, [t_i,".xml"].to_s), str_newxml)
    rescue
      error_list << path_xml
      return "Error list<br />#{error_list.join("<br />")}"
    end
  }
  
  ok_mes = "<a href='#{@uri_archives_path}'>RemakeAllHTML Succcess</a>"
  return ok_mes if error_list.empty?
  
end

def remake_onlyfile(id)
  error_list = Array.new
  require "fileutils"
  FileUtils.mkdir_p(@path_trash)
  # xml path
  path_xml = p_get_xmlpath(id)
  # xml data
  begin
    doc = m_read_xml(path_xml)
    str_xml = doc.to_s
    # save xml
    path_trash_xml = File.join(@path_trash, [id, ".xml"].to_s)
    p_remakesave( path_xml, path_trash_xml, str_xml )
    # html path
    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
    FileUtils.mkdir_p(File.join(@xhtml_dir, d_y, d_m))
    path_html = File.join(@xhtml_dir, d_y, d_m, [t_i,".html"].to_s)
    str_html = m_apply_xsl_path(str_xml, @path_xsl)
    # save html
    path_trash_html = File.join(@path_trash, [id, ".html"].to_s)
    p_remakesave( path_html, path_trash_html, str_html )
    # end of message
    ok_mes = "<a href='#{path_html.gsub!(@xhtml_dir, @uri_archives_path)}'>RemakeHTML Success</a>"
    return ok_mes if error_list.empty?
    
  rescue
    error_list << path_xml
    return "XML DATA Error <br / >#{error_list}"
  end
  
end

private
def p_remakesave(path, trash, str)
  File.rename(path, trash) if FileTest.exist?(path)
  m_write_file(path, str)
end

def p_get_xmlpath(id)
  return "Error" if id =~ /\D/ or id.empty?
  path_xml = "path"
  m_common_count_xmlfiles(@path_log_xml).each{ |line|
     path_xml = line if line =~ /#{id}/
  }
  return "Error, not found XML file" unless FileTest.exist?(path_xml)
  return path_xml
end

end

