require 'roo'

class UserStory < ActiveRecord::Base

  belongs_to :project
  
  
  def self.import_csv(proj,upload_file)
    the_stories = []
    return the_stories if upload_file.nil?
    begin 
      if RUBY_VERSION =~ /^3/

        tmp_file = upload_file["tempfile"]
        CSV.read(tmp_file.path)
        csv_data = CSV.parse(File.read(tmp_file.path), headers: true)
        csv_data.each do |row|
          story = UserStory.new(:project_id => proj.id)      
          row_data = row.to_hash       
          row_data  = row_data.transform_keys{ |key| key.to_s.downcase }          
          row_data["title"] = row_data["title"].encode(Encoding::UTF_32LE, "ISO-8859-1")  if row_data["title"]
          story.attributes = row_data # not actual saving          
          the_stories << story
        end

      else # ruby 3 with roo 2.8.3 is failing
        spreadsheet = open_spreadsheet(upload_file)
        header = spreadsheet.row(1)
        (2..spreadsheet.last_row).each do |i|
          row = Hash[[header, spreadsheet.row(i)].transpose]      
          story = UserStory.new(:project_id => proj.id)      
          row_data = row.to_hash       
          row_data  = row_data.transform_keys{ |key| key.to_s.downcase }          
          row_data["title"] = row_data["title"].encode(Encoding::UTF_32LE, "ISO-8859-1")  if row_data["title"]
          story.attributes = row_data # not actual saving          
          the_stories << story
        end    
      end
    rescue => e
      puts("[WARN] failed to parse CSV: #{e}")
    end
    return the_stories
  end
    
  def self.open_spreadsheet(upload_file)
    case File.extname(upload_file["filename"])
    when ".csv" then Roo::CSV.new(upload_file["tempfile"])
    when ".xls" then Roo::Excel.new(upload_file["tempfile"])
    when ".xlsx" then Roo::Excelx.new(upload_file["tempfile"])
    else 
      raise "Unknown file type: #{upload_file}"
    end
  end
  
	def self.to_csv(records)
	  all_column_names = column_names.dup.to_a	    
    all_column_names.delete("id")
    all_column_names.delete("created_at")
    all_column_names.delete("updated_at")
    all_column_names.delete("project_id")
        
    column_order =["external_id", "title", "description",  "points"]    
    all_sorted_column_names = all_column_names.sort_by{|name| column_order.index(name)}.to_a    
		special_column_names =  [] 
    		
		CSV.generate do |csv|
      csv << all_sorted_column_names.collect{|x| x.upcase}  + special_column_names.collect{|x| x.upcase}
      records.each do |msip|
        special_data = []
        csv << msip.attributes.values_at(*all_sorted_column_names) + special_data       
      end
    end    
  end
  
end