/*!
 * \file    /utl/com/spi.h
 * \brief   An Abstract base class interface for the spi bus
 *
 * Copyright (C) 2018 Christos Choutouridis
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation, either version 3
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */
#ifndef _utl_com_spi_h__
#define _utl_com_spi_h__

#include <utl/core/impl.h>
#include <utl/core/crtp.h>
#include <utl/meta/meta.h>

namespace utl {

/*!
 * \ingroup Communication
 * \brief   Abstract base class for spi bus
 */
//!@{

   namespace spi {
      /*!
       * SPI implementation bit order
       */
      enum class bitOrder {
         LSB_First =0x01,     //!< Most significant first
         MSB_First =0x80      //!< Less significant first
      };
      /*!
       * SPI implementation Clock Polarity
       */
      enum class cpol {
         LOW =0,  //!< LOW
         HIGH     //!< HIGH
      };
      /*!
       * SPI implementation Clock Phase
       */
      enum class cpha {
         LOW =0,  //!< LOW
         HIGH     //!< HIGH
      };
   }

   /*!
    * Template base class for SPI communication interface using CRTP
    * This class force a common interface for SPI communication
    * protocol implementations.
    * \param   impl_t   The CRTP type (the derived/implementation class typename).
    */
   template <typename impl_t>
   class spi_i {
      _CRTP_IMPL(impl_t);  //! \brief  Syntactic sugar to CRTP casting

   public:
      using type = spi_i<impl_t>;     //!< Export type as identity meta-function

   /*!
    * \name Object lifetime
    */
   //!@{
   protected:
      spi_i () = default;              //!< Allow constructor from derived only
      ~spi_i () = default;             //!< Allow destructor from derived only
      spi_i (const type&) = delete;    //!< No copies
      type& operator= (const type&) = delete;
   //!@}

   /*!
    * \name Implementation requirements
    * \note
    *    In order for the implementation to have the following as private members
    *    it also need to declare this class as friend
    */
   //! @{
   private:
      uint32_t _clock () const { return impl()._clock (); } //!< clock frequency of the bus [Hz]
      void _clock (uint32_t c) { impl()._clock (c); }       //!< set clock frequency of the bus [Hz]
      byte_t _tx_data (byte_t b) { return impl()._tx_data (b); } //!< Transmit a byte on the bus and return the response
   //! @}

   /*!
    * \name Get/Set functions provided by the interface
    */
   //!@{
   public:
      uint32_t clock () const { return _clock (); }   //!< \return clock frequency of the bus
      void clock (uint32_t c) { _clock (c); }         //!< \brief set clock frequency of the bus
   //!@}

   /*!
    * \name I/O functions provided by the interface
    */
   //!@{
   public:
      /*!
       * Transmit a byte to spi bus and return the response
       */
      byte_t tx_data (byte_t out) {
         return _tx_data (out);
      }
      /*!
       * \brief
       *    Transmit a number of bytes to the spi bus and read the response.
       * \param  out    Pointer to data to send to the bus
       * \param  in     Pointer to buffer to store the data from the bus
       * \param  n      The number of bytes to transmit/receive
       * \return        The number of bytes.
       */
      size_t tx_data (const byte_t *out, byte_t *in, size_t n);
      /*!
       * Receive a byte from spi bus while transmitting 0xFF
       */
      byte_t rx_data () {
         return _tx_data(0xFF);
      }
      /*!
       * \brief
       *    Receive a number of bytes from the spi bus while transmitting 0xFFs.
       * \param  in     Pointer to buffer to store the data
       * \param  n      The number of bytes to read
       * \return        The number of received bytes.
       */
      size_t rx_data (byte_t *in, size_t n);
   //!@}
   };

   /*!
    * \brief
    *    Transmit a number of bytes to the spi bus and read the response.
    * \param  out    Pointer to data to send to the bus
    * \param  in     Pointer to buffer to store the data from the bus
    * \param  n      The number of bytes to transmit/receive
    * \return        The number of bytes.
    */
   template<typename _I>
   size_t spi_i<_I>::tx_data (const byte_t *out, byte_t *in, size_t n) {
      for (size_t nn {n} ; nn ; --nn)
         *in++ = _tx_data (*out++);
      return n;
   }
   /*!
    * \brief
    *    Receive a number of bytes from the spi bus while transmitting 0xFFs.
    * \param  in     Pointer to buffer to store the data
    * \param  n      The number of bytes to read
    * \return        The number of received bytes.
    */
   template<typename _I>
   size_t spi_i<_I>::rx_data (byte_t *in, size_t n) {
      for (size_t nn {n} ; nn ; --nn)
         *in++ = _tx_data (0xFF);
      return n;
   }

   /*!
    * \brief
    *    A virtual base class implementation
    * \param   none
    */
   template <>
   class spi_i <virtual_tag> {
   public:
      using type = spi_i<virtual_tag>; //!< Export type as identity meta-function

   /*!
    * \name Object lifetime
    */
   //!@{
   protected:
      spi_i () = default;                    //!< Allow constructor from derived only
      spi_i (const type&) = delete;          //!< No copies
      type& operator= (const type&) = delete;
   public:
      virtual ~spi_i () = default;           //!< Virtual default destructor
   //!@}

   /*!
    * \name Implementation requirements
    */
   //! @{
   private:
      virtual uint32_t _clock () const =0;   //!< Read the clock frequency of the bus
      virtual void _clock (uint32_t) =0;     //!< Set the clock frequency of the bus
      virtual byte_t _tx_data (byte_t) =0;   //!< Transmit a byte on the bus and return the response
   //! @}

   /*!
    * \name Get/Set functions provided by the interface
    */
   //!@{
   public:
      uint32_t clock () const { return _clock (); }   //!< \return clock frequency of the bus
      void clock (uint32_t c) { _clock (c); }         //!< \brief set clock frequency of the bus
   //!@}

   /*!
    * \name I/O functions provided by the interface
    */
   //!@{
   public:
      /*!
       * Transmit a byte to spi bus and return the response
       */
      byte_t tx_data (byte_t out) {
         return _tx_data (out);
      }
      /*!
       * \brief
       *    Transmit a number of bytes to the spi bus and read the response.
       * \param  out    Pointer to data to send to the bus
       * \param  in     Pointer to buffer to store the data from the bus
       * \param  n      The number of bytes to transmit/receive
       * \return        The number of bytes.
       */
      size_t tx_data (const byte_t *out, byte_t *in, size_t n);
      /*!
       * Receive a byte from spi bus while transmitting 0xFF
       */
      byte_t rx_data () {
         return _tx_data (0xFF);
      }
      /*!
       * \brief
       *    Receive a number of bytes from the spi bus while transmitting 0xFFs.
       * \param  in     Pointer to buffer to store the data
       * \param  n      The number of bytes to read
       * \return        The number of received bytes.
       */
      size_t rx_data (byte_t *in, size_t n);
   //!@}

   };

   /*!
    * \brief
    *    Transmit a number of bytes to the spi bus and read the response.
    * \param  out    Pointer to data to send to the bus
    * \param  in     Pointer to buffer to store the data from the bus
    * \param  n      The number of bytes to transmit/receive
    * \return        The number of bytes.
    */
   size_t spi_i<virtual_tag>::tx_data (const byte_t *out, byte_t *in, size_t n) {
      for (size_t nn {n} ; nn ; --nn)
         *in++ = _tx_data (*out++);
      return n;
   }
   /*!
    * \brief
    *    Receive a number of bytes from the spi bus while transmitting 0xFFs.
    * \param  in     Pointer to buffer to store the data
    * \param  n      The number of bytes to read
    * \return        The number of received bytes.
    */
   size_t spi_i<virtual_tag>::rx_data (byte_t *in, size_t n) {
      for (size_t nn {n} ; nn ; --nn)
         *in++ = _tx_data (0xFF);
      return n;
   }



/*!
 * i2c interface concept
 */
//! @{
#if defined _utl_have_concepts
   template <typename T>
   concept bool Spi_i = requires (T t, const T ct, typename T::Sequence s) {
      // Object type
      requires not_<std::is_copy_constructible<T>::value>::value;
      requires not_<std::is_copy_assignable<T>::value>::value;
      // Methods
      {ct.clock()} -> uint32_t;
      {t.clock(0)} -> void;
      {t.tx_data(1)} -> byte_t;
      {t.rx_data()}  -> byte_t;
   };
#else
   namespace spi_i_details {
      using std::declval;

      template <class _Tp> using try_cclock_t= decltype (declval<const _Tp>().clock());
      template <class _Tp> using try_clock_t = decltype (declval<_Tp>().clock(declval<uint32_t>()));
      template <class _Tp> using try_tx_t    = decltype (declval<_Tp>().tx_data(declval<byte_t>()));
      template <class _Tp> using try_rx_t    = decltype (declval<_Tp>().rx_data());

      //! Primary template to catch any non SPI interface types
      template <typename _Tp, typename =void>
      struct is_spi_ : meta::false_ {};

      //! template to catch a proper SPI interface type
      template <typename _Tp>
      struct is_spi_ <
         _Tp,
         meta::void_t <
            meta::use_if_same_t <try_cclock_t<_Tp>, uint32_t>,
            meta::use_if_same_t <try_clock_t<_Tp>,  void>,
            meta::use_if_same_t <try_tx_t<_Tp>,     byte_t>,
            meta::use_if_same_t <try_rx_t<_Tp>,     byte_t>
         >
      > : meta::true_ {};
   }
   /*!
    * Value meta-programming function for SPI interface checking
    * \param   _Tp  Type to check
    * \return  True if _Tp is a spi interface
    */
//   template <typename _Tp>
//   constexpr bool Spi_i = spi_i_details::is_spi_<_Tp>::value;
#endif
//! @}

//! @}

}  // namespace utl

#endif /* #ifndef _utl_com_spi_h__ */
