// ****************************************************************************
//
//          Aevol - An in silico experimental evolution platform
//
// ****************************************************************************
//
// Copyright: See the AUTHORS file provided with the package or <www.aevol.fr>
// Web: http://www.aevol.fr/
// E-mail: See <http://www.aevol.fr/contact/>
// Original Authors : Guillaume Beslon, Carole Knibbe, David Parsons
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 2 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
// ****************************************************************************

#ifndef AEVOL_DNAFACTORY_H
#define AEVOL_DNAFACTORY_H

#include <list>
#include <vector>

#include "Dna.h"

namespace aevol {

enum DnaFactory_Policy {
    FIRST = 0,
    FIRSTFIT = 1,
    BESTFIT = 2,
    LOCAL_GLOBAL_FIT = 3,
    ALLOCATE = 4
};

enum DnaFactory_Garbage_Policy {
    MAXSIZE = 0,
    MAXMEM = 1
};

class Population;

class DnaFactory {
  friend class Dna;

 public:
  DnaFactory() = delete;
  DnaFactory(const DnaFactory&) = delete;
  DnaFactory(DnaFactory&&) = delete;
  DnaFactory& operator=(const DnaFactory&) = delete;
  DnaFactory& operator=(DnaFactory&&) = delete;
  ~DnaFactory();

  DnaFactory(DnaFactory_Policy policy, int pool_size, Dna::size_type init_size, int pop_size = -1);

  void reduce_space(const Population& population);

  constexpr const static int32_t cleanup_step = 100;

 protected:
  void init(Dna::size_type init_size, int pop_size = -1);

  Dna* get_dna(Dna::size_type request_size);

  void give_back(Dna* dna);

  const static DnaFactory_Garbage_Policy garbage_policy = DnaFactory_Garbage_Policy::MAXMEM;

  std::list<Dna*> list_unused_dna_;
  std::vector<std::list<Dna*>> local_list_unused_dna_;
  DnaFactory_Policy policy_;
  int pool_size_;

  int global_pool_size_   = 256;
  size_t local_pool_size_ = 256;

  size_t max_pool_size = 16000;
};

// Static instance
extern std::unique_ptr<DnaFactory> dna_factory;

}  // namespace aevol

#endif  //AEVOL_DNAFACTORY_H
