{{!
  Copyright (c) HashiCorp, Inc.
  SPDX-License-Identifier: MPL-2.0
}}

<StateChart
  @src={{chart}}
as |State Guard Action dispatch state|>

  <Guard
    @name="hasToken"
    @cond={{action 'hasToken'}}
  />
  <Action
    @name="login"
    @exec={{action 'login'}}
  />
  <Action
    @name="logout"
    @exec={{action 'logout'}}
  />

  {{! This DataSource just permanently listens to any changes to the users }}
  {{! token, whether thats a new token, a changed token or a deleted token }}
  <DataSource
    @src={{@src}}
    @onchange={{queue (action (mut token) value="data") (action dispatch "CHANGE") (action (mut previousToken) value="data")}}
  />
  {{! This DataSink is just used for logging in from the form, }}
  {{! or logging out via the exposed logout function }}
  <DataSink
    @sink={{@sink}}
    as |sink|
  >
    {{#let (hash
      login=(action sink.open)
      logout=(action sink.open null)
      token=token
    ) as |api|}}

      <State @matches="authorized">
        {{yield api to="authorized"}}
      </State>

      <State @matches="unauthorized">
        {{yield api to="unauthorized"}}
      </State>

    {{/let}}
  </DataSink>
</StateChart>
