###############################################################################
# mod_uploader / item-manager.rb
###############################################################################
# Copyright (C) 2005 Tetsuya Kimata <kimata@acapulco.dyndns.org>
#
# All rights reserved.
#
# This software is provided 'as-is', without any express or implied
# warranty.  In no event will the authors be held liable for any
# damages arising from the use of this software.
#
# Permission is granted to anyone to use this software for any
# purpose, including commercial applications, and to alter it and
# redistribute it freely, subject to the following restrictions:
#
# 1. The origin of this software must not be misrepresented; you must
#    not claim that you wrote the original software. If you use this
#    software in a product, an acknowledgment in the product
#    documentation would be appreciated but is not required.
#
# 2. Altered source versions must be plainly marked as such, and must
#    not be misrepresented as being the original software.
#
# 3. This notice may not be removed or altered from any source
#    distribution.
#
# $Id: item-manager.rb 646 2005-09-08 01:23:14Z svn $
###############################################################################

require 'erb'
require 'upload-item'

class ItemManager
  include ERB::Util

  TEMPLATE_DIR	        = "tmpl"
  VIEW_TEMPLATE         = "view.htm"
  ERROR_TEMPLATE   		= "error.htm"
  PER_PAGE_ITEM_NUMBER  = 20

  def initialize(uploader_url, file_dir, thumb_dir, thumb_ext)
    @uploader_url   = uploader_url
    @file_dir       = file_dir
    @thumb_dir      = thumb_dir
    @thumb_ext      = thumb_ext
    @view_tmpl      = load_template(TEMPLATE_DIR + "/" + VIEW_TEMPLATE)
    @error_tmpl     = load_template(TEMPLATE_DIR + "/" + ERROR_TEMPLATE)
  end

  def view_page(current_page)
    item_list = load_item_list

    uploader_url = @uploader_url

    total_file_size = item_list.total_file_size
    total_file_number = item_list.size
    
    page_number = (item_list.size == 0) ? 1 \
                                        : (item_list.size-1)/PER_PAGE_ITEM_NUMBER + 1
    current_page = (current_page > page_number) ? page_number : current_page;

    item_list = item_list.to_h((current_page-1)*PER_PAGE_ITEM_NUMBER, PER_PAGE_ITEM_NUMBER)
    
    return @view_tmpl.result(binding)
  end

  def load_item_list
    UploadItemList.load(@file_dir, @thumb_dir, @thumb_ext)
  end

  def load_template(tmpl_path)
    ERB.new(File.read(tmpl_path))
  end

  def remove_page(file_path, page)
    item_list = load_item_list

    begin
      item_list.remove(file_path)

      return view_page(page)
    rescue Exception
      return error_page($!.message)
    end
  end

  def error_page(error_message)
    return @error_tmpl.result(binding)
  end

  private :load_template, :error_page
end

# local Variables:
# mode: ruby
# buffer-file-coding-system: euc-japan-dos
# End:
