#!/usr/bin/ruby

require 'shellwords'

class TaskFileParser
  attr_accessor :action, :event, :items, :variables

  def initialize(task_file)
    @task_file = task_file
    @action, @event, @items = []
    @variables = {}
  end
  
  def parse
    processing_items = false
    items_string = ""
      
    File.open(@task_file, "r").each_line do |line|
      if processing_items
        items_string += line
      else
      
        case
        when /(^ACTION:) (.*)/.match(line)
          @action = remove_quotes($2)
        when /(^EVENT:) (.*)/.match(line)
          @event = remove_quotes($2)
        when /(^VARIABLE:) (.*)/.match(line)
          var_split = Shellwords.split($2)
          @variables[var_split[0]] = var_split[1]
        when /(^ITEMS:) (.*)/.match(line)
          items_string += line
          processing_items = true
        end
      end
    end
    
    if items_string != ""
      if @variables["dragged_type"] == "files"
        @items = Shellwords.split(items_string[7..-1])
      else
        @items = [items_string[8..-2]]
      end
    end

    unless @action and @event
      puts "Invalid Task Description file"
      return false
    end
    
    return true
  end
  
  def remove_quotes(str)
    str[1..-1].chomp("\"")
  end

end