module Comm
  module Module
    #= 配列からCSVファイルを生成する
    class CsvWriter
      require 'fastercsv'
      require 'nkf'
      include Comm::Const::Print
      def initialize(opts={})
        @tmp_path =  opts[:tmp_path] ? opts[:tmp_path] : Dir.tmpdir+'/'+rand(100000).to_s+Time.now.to_i.to_s
      end
      #== 書き込み
      #   入力arrayは配列の配列
      def write(parent_array, org_opts={})
        opts = {:response=>true}.update(org_opts)
        FasterCSV.open(@tmp_path, 'w', {:force_quotes=>true}) do |csv|
          parent_array.each do |org|
            csv << org.map{|val| val ? NKF.nkf('-W -s', val.to_s) : ""}
          end
        end
        return_hash = {:success=>opts[:response],
                       :file_name=>get_file_name(opts),
                       :tmp_file_name=>@tmp_path,
                       :file_type=>get_file_type}
        return_hash[:message] = opts[:message] if opts[:message]
        return return_hash
      end
      
      def get_file_name(opts={})
        unless opts[:basename]
          opts[:basename] = @mcls ? @mcls.name.underscore : ''
        end
        opts[:uniqstr] ||= Time.now.strftime("%y%m%d-%H%M")
        opts[:extension] ||= '.csv'
        return opts[:basename]+'-'+opts[:uniqstr]+opts[:extension]
      end
      
      def get_file_type
        return FILE_TYPE_INFO[2][:ctype]
      end
    end
  end
end
