module Comm
  module Module
    class OutputCsv  < Comm::Module::OutputSpreadSheet
      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
        @no_header = opts[:spread_sheet_no_header]==STR_TRUE
        super
      end
      
      def output(hr, col_info)
        begin
          FasterCSV.open(@tmp_path, 'w', {:force_quotes=>true}) do |csv|
            unless @no_header
              header = []
              col_info.length.times do |i|
                value = col_info[i.to_s]
                tmp_value = NKF.nkf('-W -s -x', value["v"])
                #listの場合はid/code用のカラムを足す
                if value["t"]=="list" and output_field?(value['f'].strip) and value["a"].blank?
                  header.push(tmp_value+"(ID)")
                end
                header.push(tmp_value)
              end
              csv << header
            end
            regex_simple_int = Regexp.new('^\d+$')
            for hash in hr
              cr = []
              col_info.length.times do |i|
                value = col_info[i.to_s]
                field = value['f']
                if field == nil
                  field = ''
                else
                  tmp_value = hash[field.strip].to_s
                  if tmp_value.blank? && field =~ regex_simple_int
                    tmp_value = hash[field.to_i]
                  end
                end
                sum_up_if_need(field, tmp_value) if @total_temp
                if value["t"]=="list" 
                  if output_field?(field) && value["a"].blank?
                    cr.push(NKF.nkf('-W -s -x', tmp_value.to_s))
                  end
                  key = field.gsub(/(_code|_id)$/,(value["a"].blank? ? '_dn' : ('_'+value["a"])))
                  tmp_value = hash[key].to_s
                  cr.push(NKF.nkf('-W -s -x', tmp_value))
                else
                  cr.push(NKF.nkf('-W -s -x', tmp_value.to_s))
                end
              end
              csv << cr
            end
            if @total_temp
              cr = []
              col_info.length.times do |i|
                value = col_info[i.to_s]
                field = value['f'].strip
                val = output_sum_ups(field)
                cr.push(NKF.nkf('-W -s -x', val.to_s))
                if value["t"]=="list" and output_field?(field)
                  cr.push(NKF.nkf('-W -s -x', ''))
                end
              end
              csv << cr
            end
          end
          treat_additions_on_end(hr, col_info)
          return {:success=>true,
                  :file_name=>get_file_name,
                  :tmp_file_name=>@tmp_path,
                  :file_type=>get_file_type}.update(add_keys_to_reply)
        rescue => e
          raise e
        end
      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
