# Copyright (C) 2003-2005 Kouichirou Eto, All rights reserved.

$LOAD_PATH << "../../lib" unless $LOAD_PATH.include?("../../lib")

module Qwik
  class Action
    # ============================== icon
    def icon_path(type)
     #suf= "png"
      suf= "gif"
      path = @config.theme_dir.path+"icons"
      file = type+"."+suf
      return nil unless (path+file).exist?
      return ".theme/icons/"+file
    end

    ICON_SUF_TABLE = {
      "tgz" => "tar",
    }

    ICON_MIMETYPE_TABLE = {
      "application/octet-stream" => "binary",
      "application/pdf" => "pdf",
      "application/postscript" => "ps",
      "application/zip" => "compressed",
    }

    ICON_GENRE_TABLE = {
      "application" => "a",
      "audio" => "sound2",
      "image" => "image2",
      "message" => "text",
      "model" => "sphere2",
      "multipart" => "text",
      "text" => "text",
      "video" => "movie",
    }

    def icon_find(ext)
      ext.downcase!

      type = ICON_SUF_TABLE[ext]
      return icon_path(type) if type

      mimetype = @res.mimetypes[ext]
      if mimetype
	type = ICON_MIMETYPE_TABLE[mimetype]
	if type
	  path = icon_path(type)
	  return path if path
	end

	genre, spec = mimetype.split("/")
	type = ICON_GENRE_TABLE[genre]
	if type
	  path = icon_path(type)
	  return path if path
	end
      end

      return icon_path("generic")
    end

    def is_image?(ext)
      ext.downcase!
      mimetype = @res.mimetypes[ext]
      return false if mimetype.nil?
      genre, spec = mimetype.split("/")
      return genre == "image"
    end
  end
end

if $0 == __FILE__
  require "t/test"
  $debug = true
end

if $debug
  class TC_ActIcon < Test::Unit::TestCase
    include TestSession

    def test_all
      # test_find_icon
      session("/")
      assert_equal(".theme/icons/tar.gif", @action.icon_find("tgz"))
      assert_equal(".theme/icons/text.gif", @action.icon_find("txt"))
      assert_equal(".theme/icons/text.gif", @action.icon_find("css"))
      assert_equal(".theme/icons/image2.gif", @action.icon_find("png"))
      assert_equal(".theme/icons/image2.gif", @action.icon_find("gif"))
      assert_equal(".theme/icons/pdf.gif", @action.icon_find("pdf"))
      assert_equal(".theme/icons/ps.gif", @action.icon_find("ps"))
      assert_equal(".theme/icons/compressed.gif", @action.icon_find("zip"))
      assert_equal(".theme/icons/binary.gif", @action.icon_find("exe"))
      assert_equal(".theme/icons/generic.gif", @action.icon_find("nosuchext"))

      # test is_image?
      assert_equal(true, @action.is_image?("jpg"))
      assert_equal(true, @action.is_image?("jpeg"))
      assert_equal(true, @action.is_image?("JPG"))
      assert_equal(true, @action.is_image?("png"))
      assert_equal(true, @action.is_image?("gif"))
      assert_equal(true, @action.is_image?("bmp"))
      assert_equal(true, @action.is_image?("ico"))
      assert_equal(true, @action.is_image?("ppm"))
      assert_equal(false, @action.is_image?("pdf"))
    end
  end
end
