import(mod_dlg);
import(mod_conference);

initial state START;
transition "got INVITE in callee leg" START - invite -> RUN_INVITE;
transition "session starts in callee leg" START - sessionStart / {
  sets($prompt_name=$(config.prompt_path)/welcome_callee.wav)
  playFile($prompt_name);
} -> ENTER_PIN;

state RUN_INVITE
 enter {
   logAll(3);
 };

state ENTER_PIN;

transition "got cancel from A leg" (START, RUN_INVITE, ENTER_PIN) - event(#a_status==CANCEL) / stop(true) -> END;

transition "pressed a number" ENTER_PIN - key(#key<10) / {
  flushPlaylist(); 
  append($entered_pin, #key);
} -> TEST_PIN;
transition "pressed hash or start" ENTER_PIN - key / flushPlaylist() -> TEST_PIN_FINAL;

state TEST_PIN
 enter {
   repost();
 };
transition "pin matches" TEST_PIN - test($pin==$entered_pin) -> MATCHING_PIN;
transition "pin doesn't match" TEST_PIN - test($pin!=$entered_pin) -> ENTER_PIN;

state TEST_PIN_FINAL
 enter {
   repost();
 };
transition "pin matches" TEST_PIN_FINAL - test($pin==$entered_pin) -> MATCHING_PIN;
transition "pin doesn't match" TEST_PIN_FINAL - test($pin!=$entered_pin) / {
  clear($entered_pin);
  sets($prompt_name=$(config.prompt_path)/sorry_pin_wrong.wav)
  playFile($prompt_name);
}  -> ENTER_PIN;

state MATCHING_PIN
 enter {
   set($b_status=MATCHED);
   set($b_ltag=@local_tag);
   postEvent($a_ltag, b_status;b_ltag);
   conference.join($a_ltag);
   repost();
 }; 
transition "ok, connected" MATCHING_PIN --> CONNECTED;

state CONNECTED;

transition "BYE received" CONNECTED - hangup / {
  set($b_status=BYE);
  postEvent($a_ltag, b_status);
  stop(false);
} -> END;

transition "BYE in other leg" CONNECTED - event(#a_status==BYE) / {
  stop(true);
} -> END;

state END;