#coding=utf-8

module Trustie
  module Utils
    class Image
      def initialize(file, bak=false)
        @file = file
        @bak = bak
      end

      def bitmap?(data)
        data[0,2]==77.chr + 66.chr
      end

      def gif?(data)
        data[0,4]==71.chr + 73.chr + 70.chr + 56.chr
      end

      def jpeg?(data)
        data[0,3]== 0xff.chr + 0xd8.chr + 0xff.chr
      end
      def png?(data)
        data[0,2]==0x89.chr + 80.chr
      end

      def image?
        data = ''
        if @file.respond_to?(:read)
          data = @file.read(9)
          @file.rewind
        end
        return false if data.size < 9
        bitmap?(data) || gif?(data) || jpeg?(data) || png?(data)
      end

      def compress(size=300)
        backup if @bak
        begin
          f = Magick::ImageList.new(@file)
          if f.format != 'GIF'
            width = size
            if f[0].columns > width
              proportion = (width/f[0].columns.to_f)
              height = (f[0].rows*proportion)
              f.resize_to_fill!(width,height.to_i)
              f.write(@file)
            end
          end
        rescue Exception => e
          Rails.logger.error "[Error] compress : ===> #{e}"
        end
      end

      def backup
        FileUtils.cp @file, "#{@file}.bak" 
      end

    end
  end
end
