module Import
  class StatementImport

    class << self
      def run!
        import_files.each do |import_file|
          instance = new(import_file).extend(importer)
          instance.run!
        end
      end

      def import_files
        Dir.glob(AppConfig['import']['files_pattern'])
      end

      def importer
        AppConfig['import']['importer'].constantize
      end
    end

    def initialize(csv_file)
      @csv_file = csv_file
    end

    def csv_lines
      @_lines ||= read_lines(@csv_file)
    end

    def run!
      message = []
      print_csv_info
      imported_rows = 0
      csv_lines.each do |csv_line|
        next if skip_line?(csv_line)
        line = StatementLine.find_by_import_unique_id(csv_line.unique_id)
        unless line
          message << "importing #{csv_line.to_s} ... "
          begin
            line = StatementLine.create_from_csv_line!(csv_line)
            imported_rows += 1
            message << "   done."
          rescue ActiveRecord::RecordInvalid => e
            message << "failed "
            message << "Error: #{e.message}"
            message << "Kategorie: #{csv_line.category}"
            next
          end
        end
      end
      message << "Latest file has bookings from #{csv_lines.earliest_booking} to #{csv_lines.latest_booking}."
      message << "Imported #{imported_rows} of #{csv_lines.size} those statement(s)."
      puts message
      message
    end

    private

      def print_csv_info
        puts "CSV has #{csv_lines.num_statements} statement lines from #{csv_lines.earliest_booking} to #{csv_lines.latest_booking}."
      end

      def skip_line?(line)
        line.prebooking? # prebookings are announcements only.
      end

  end

end