require 'bundler/setup'
require 'rubygems'
require 'ruote'

MODE = (ARGV.size == 1 && ARGV[0] == 'update') ? :update : :proceed
$fei_sid = nil

class TestParticipant1 < Ruote::StorageParticipant
  def on_workitem
    super
    $fei_sid = workitem.fei.sid

    puts "TestParticipant1 :: About to set a workitem field."
    workitem.fields["fieldname"] = "The value!"
    puts "TestParticipant1 :: The workitem field was set!"

    case MODE
      when :update
        puts "TestParticipant1 :: About to update."
        update(workitem)
        puts "TestParticipant1 :: Done with update."
      when :proceed
        puts "TestParticipant1 :: About to proceed."
        proceed(workitem)
        puts "TestParticipant1 :: Done with proceed."
    end
  end
end

class TestParticipant2 < Ruote::StorageParticipant
  def on_workitem
    super
    puts "TestParticipant2 :: Getting the workitem field."
    field_value = workitem.fields["fieldname"]


    if field_value == 'The value!'
      puts "TestParticipant2 :: Got this value: #{field_value.inspect}.  This is the expected result!"
    else
      puts "TestParticipant2 :: Got this value: #{field_value.inspect}.  But it was supposed to be 'The value!'."
    end

    proceed(workitem)
  end
end

engine = Ruote::Dashboard.new(Ruote::Worker.new(Ruote::HashStorage.new))

engine.register do
  participant 'test_1', TestParticipant1
  participant 'test_2', TestParticipant2
end

pdef = Ruote.process_definition do
  test_1
  test_2
end

wfid = engine.launch(pdef)

if MODE == :update
  sleep(1)
  puts "Slept for 1 second. TestParticipant1's on_workitem should be updated by now.  Call proceed from this thread."
  engine.storage_participant.proceed(engine.storage_participant[$fei_sid])
  puts "Called proceed on TestParticipant1"
end

engine.wait_for(wfid)

if (engine.process(wfid) && engine.process(wfid).errors.count > 0)
  engine.process(wfid).errors.each do |err|
    puts "Error: #{err.message}"
  end
end

