/*
  uid.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 "rdm.h"
#include <cstdint>

namespace RDM {

/**
 * @brief The UID struct
 */
struct UID {
  /**
   * @brief UID
   * @param dev
   * @param man
   * @param flag
   */
  UID(uint32_t dev = 0, uint16_t man = 0, bool flag = false)
    : device(dev)
    , esta_man(man)
    , flag(flag)
  {};
  union {
    uint64_t uid : 48;
    struct __attribute__((packed)) {
      uint32_t device;
      union {
        uint16_t manufacturer;
        struct {
          uint16_t esta_man : 15;
          bool     flag     : 1;
        };
      };
    };
  };
  /**
   * @brief isBroadcast
   * @return
   */
  bool isBroadcast() const {
    return (uid == BROADCAST_ALL_DEVICES_ID || device == ALL_DEVICE_ID_MASK);
  }
  /**
   * @brief operator ==
   * @param a
   * @param b
   * @return
   */
  friend bool operator== (const UID& a, const UID& b)
  {
    if (a.uid == BROADCAST_ALL_DEVICES_ID || b.uid == BROADCAST_ALL_DEVICES_ID)
      return true;
    if (a.device == ALL_DEVICE_ID_MASK || b.device == ALL_DEVICE_ID_MASK)
      return (a.esta_man == b.esta_man);
    return (a.uid == b.uid);
  }
  /**
   * @brief operator !=
   * @param a
   * @param b
   * @return
   */
  friend bool operator!= (const UID& a, const UID& b)
  {
    return !(a == b);
  }
};

} // namespace RDM
