/*
  sdt/session.h

  Copyright (c) 2021 Kevin Matz (kevin.matz@gmail.com)

  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:

  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  SOFTWARE.
*/
#pragma once

#include "channel.h"
#include "sdt.h"

#include <memory>
#include <unordered_map>

namespace ACN::SDT {

/**
 * @brief 3.1 Session Identity
 */
struct SessionId {
  UUID::uuid  cid;      //!< the component ID (CID) of the session leader
  uint16_t    number;   //!< the session number the leader has assigned
  uint32_t    protocol; //!< the ID of the protocol carried by the session
  bool operator== (const SessionId &) const;
};

/**
 * @brief The Session class
 *  A session has a single leader and zero or more session members. The leader
 *  communicates to members using the downstream address. Members respond to
 *  the leader on the upstream address. A unique session identifier identifies
 *  a session.
 */
class Session {
public:
  Session();
  ~Session();

  SessionId id();

  // 4.4 SDT Base Layer Messages (non ad-hoc)
  void join_accept();
  void join_refuse();
  void leaving();
  void nak();
  void reliable_wrapper();
  void unreliable_wrapper();

  // 4.5 SDT Wrapped Messages
  void ack();
  void channel_params();
  void leave();
  void connect();
  void connect_accept();
  void connect_refuse();
  void disconnect();
  void disconnecting();

protected:
  std::shared_ptr<ACN::Component> leader;       //!< session leader
  std::shared_ptr<Channel>        downstream;   //!< downstram channel
  std::unordered_map<MID, std::shared_ptr<Channel>> upstream; //!< upstream channel

private:
  uint16_t number_;
  uint32_t protocol_;
  MID next_id_ = 1;
};


} // namespace ACN::SDT
