/*
 * observe_pattern.hpp
 *
 *  Created on: 18 мар. 2019 г.
 *      Author: alexrayne <alexraynepe196@gmail.com>
  ------------------------------------------------------------------------
    Copyright (c) alexrayne

   All rights reserved.
   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions are met:
   - Redistributions of source code must retain the above copyright
     notice, this list of conditions and the following disclaimer.
   - Redistributions in binary form must reproduce the above copyright
     notice, this list of conditions and the following disclaimer in the
     documentation and/or other materials provided with the distribution.
   - Neither the name of ARM nor the names of its contributors may be used
     to endorse or promote products derived from this software without
     specific prior written permission.
   *
   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
   AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE
   LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
   CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
   SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
   INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
   CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
   ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
   POSSIBILITY OF SUCH DAMAGE. *
 */

#ifndef LIB_OBSERVE_PATTERN_HPP_
#define LIB_OBSERVE_PATTERN_HPP_

#include <ctime>
#include <algorithm>



// это вызывалка методов обозревателей
// TStore предоставляет тип IObserver
// IObserver должен предоставить метод process( ...  для обработки событий

template <typename TStore>
class ObservableAction : public TStore{
public:
    using typename TStore::IObserver;
    using TStore:: observers_count;
    using TStore::observers;

    template < typename ... Args >
    void process_observers(Args ... args ){
        unsigned limit = observers_count();
        for (unsigned i=0; i < limit; i++){
          if (observers[i] != nullptr) {
              observers[i]->process(args...);
          }
        }
    }

    template < typename ... Args >
    void update_observers(Args ... args ){
        unsigned limit = observers_count();
        for (unsigned i=0; i < limit; i++){
          if (observers[i] != nullptr) {
              observers[i]->update(args...);
          }
        }
    }

    typedef ObservableAction<TStore> observe_t;
    observe_t* as_observable() {return static_cast<observe_t*>(this);}
    const observe_t* as_observable() const {return static_cast<const observe_t*>(this);}

};

// если обозревателей не ожидается много, или известно что их ограниченое количество
// статический массив уакзателей будет самым простым и мобильным способ организации их коллекции
template <typename TObserver, unsigned observableSize>
class staticObservableStore{
    public:
        typedef TObserver IObserver;
        enum { observersLimit = observableSize };

        void init () {
          observers_last = 0;
        }

        
        //virtual 
        void addObserver(IObserver* observer) {
            for (unsigned i=0; i < observers_last; i++){
              if ( observers[i] == observer )
                  return;
            }
          if(observers_last < observersLimit)
            observers[observers_last++] = observer;
        }
      
        //virtual 
        void dropObserver(IObserver* observer) {
            for (unsigned i=0; i < observers_last; i++){
              if ( observers[i] == observer ){
                  observers[i] = nullptr;
                  return;
              }
            }
        }

    protected:
        IObserver* observers[observersLimit];
        unsigned  observers_last;
        unsigned  observers_count() const {return observers_last;}
};

#include <vector>
#include "system_heap.h"

// если обозревателей неизветсно сколько, или их может быть весьма разное количество
// ипользование динамического вектора на хипе может быть адекватно

template <typename TObsetver, int observableSize = 2>
class varObservableStore {
public:
  typedef TObsetver IObserver;
  typedef std::vector< IObserver* , SystemHeap< IObserver* > > view_vector;

  void init () 
  {
  }

  //virtual 
  void addObserver(IObserver* observer) {
      if (std::find( observers.cbegin(), observers.cend(), observer ) != observers.cend() )
          return;

    if(observers_count() == 0)
      observers.reserve(observableSize);
    
    unsigned last = observers_count();
    for (unsigned i = 0; i < last; ++i ){
        if (observers[i] == nullptr){
            observers[i] = observer;
            return;
         }
    }
    observers.resize( last + 1);
    observers[last] = observer;
  }

  //virtual 
  void dropObserver(IObserver* observer) {
      unsigned limit = observers_count();
      for (unsigned i=0; i < limit; i++){
        if ( observers[i] == observer ){
            observers[i] = nullptr;
            return;
        }
      }
  }

protected:
    view_vector observers;
    unsigned observers_count() const {return observers.size();}
};





// эти информаторы должен уметь вызывать произвольные методы process, update
// обозревателей. просто хорошие сокращения больших шаблонов

template<typename T, int observableSize>
class ObservableInformer 
        : public ObservableAction< staticObservableStore<T, observableSize> > 
{
public:
    typedef staticObservableStore<T, observableSize> observer_store_t;
    typedef T IObserver;
};

template<typename T, int observablePreserve = 4>
class varObservableInformer 
        : public ObservableAction< varObservableStore<T, observablePreserve> > 
{
public:
    typedef varObservableStore<T, observablePreserve> observer_store_t;
    typedef T IObserver;
};


// единичнаая связь с ОДНИМ Обозревателем.
//  Автоматично удаляется из обозревателя при дестрое объекта.
template< typename TObservable>
class ObserverLink : public TObservable::IObserver
{
public:
    typedef TObservable             observable_t;
    typedef typename TObservable::IObserver  observer_t;

    ObserverLink():observe_obj(nullptr){}

    ~ObserverLink(){
        if (observe_obj != nullptr)
            observe_obj->dropObserver( this );
        observe_obj = nullptr;
    }

    void observe(observable_t* src){
        if (observe_obj != nullptr)
            observe_obj->dropObserver(this);
        observe_obj = src;
        if (observe_obj != nullptr)
            observe_obj ->addObserver(this);
    }

protected:
    observable_t*   observe_obj;
};


//---------------------------------------------------------------------------
//  LEGACY
typedef time_t sec_t;

template <typename T, typename Tstamp = sec_t>
class Observer {
public:
    typedef T       value_t;
    typedef Tstamp  stamp_t;
    virtual void process(T chunk, Tstamp ts) { (void)chunk; (void)ts;}
    virtual void update(Tstamp ts) { (void)ts; }

    //alias to avoid dynamic_casts
    Observer<T, Tstamp>& as_observer(){return *this;}

private:

};


template <typename T, int observableSize>
class staticObservable {
public:
  typedef Observer<T> IObserver;
  enum { observersLimit = observableSize };

  void init () {
    observers_count = 0;
  }

  virtual 
  void addObserver(IObserver* observer) {
      for (int i=0; i < observers_count; i++){
        if ( observers[i] == observer )
            return;
      }
    if(observers_count < observersLimit)
      observers[observers_count++] = observer;
  }

  virtual 
  void dropObserver(IObserver* observer) {
      for (int i=0; i < observers_count; i++){
        if ( observers[i] == observer ){
            observers[i] = nullptr;
            return;
        }
      }
  }

  virtual 
  void process_observers(T chunk, sec_t ts) {
    for (int i=0; i < observers_count; i++){
      observers[i]->process(chunk, ts);
    }
  }

  virtual 
  void update_observers(sec_t ts) {
    for (int i=0; i < observers_count; i++){
      observers[i]->update(ts);
    }
  }

protected:
    IObserver* observers[observersLimit];
    int observers_count;
};




#include <vector>
#include "system_heap.h"

template <typename T, int observableSize = 2>
class varObservable {
public:
  typedef Observer<T> IObserver;
  typedef std::vector< IObserver* , SystemHeap< IObserver* > > view_vector;

  void init () 
  {
  }

  virtual 
  void addObserver(IObserver* observer) {
      if (std::find( observers.cbegin(), observers.cend(), observer ) != observers.cend() )
          return;

    if(observers_count() == 0)
      observers.reserve(observableSize);
    
    unsigned last = observers_count();
    for (unsigned i = 0; i < last; ++i ){
        if (observers[i] == nullptr){
            observers[i] = observer;
            return;
         }
    }
    observers.resize( last + 1);
    observers[last] = observer;
  }

  virtual 
  void dropObserver(IObserver* observer) {
      unsigned limit = observers_count();
      for (unsigned i=0; i < limit; i++){
        if ( observers[i] == observer ){
            observers[i] = nullptr;
            return;
        }
      }
  }

  virtual 
  void process_observers(T chunk, sec_t ts) {
    unsigned limit = observers_count();
    for (unsigned i=0; i < limit; i++){
      if (observers[i] != nullptr)
        observers[i]->process(chunk, ts);
    }
  }

  virtual 
  void update_observers(sec_t ts) {
    unsigned limit = observers_count();
    for (unsigned i=0; i < limit; i++){
      if (observers[i] != nullptr)
        observers[i]->update(ts);
    }
  }

protected:
    view_vector observers;
    unsigned observers_count() const {return observers.size();}
};



#endif /* LIB_OBSERVE_PATTERN_HPP_ */
