/*
 * Copyright (C) 2018-2020 std::gregwar, Solarus - http://www.solarus-games.org
 *
 * Solarus 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 3 of the License, or
 * (at your option) any later version.
 *
 * Solarus 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/>.
 */
#pragma once

#include "solarus/core/InputEvent.h"
#include "solarus/core/ControlsPtr.h"
#include "solarus/core/Command.h"

#include <set>

namespace Solarus {

class MainLoop;
class Game;

/**
 * @brief Holds all of the current Commands object and dispatches the input into them
 */
class ControlsDispatcher
{
  friend class Controls;
public:
  ControlsDispatcher(MainLoop& main);
  static ControlsDispatcher& get();
  void notify_input(const InputEvent& event);
  ControlsPtr create_commands_from_game(Game& game);
  ControlsPtr create_commands_from_keyboard();
  ControlsPtr create_commands_from_joypad(const JoypadPtr& joypad);
  void add_commands(const ControlsPtr& cmds);
private:
  static ControlsDispatcher* instance;

  void remove_commands(const std::weak_ptr<Controls>& cmds);

  struct WeakPtrCmp {
      bool operator() (const std::weak_ptr<Controls> &lhs, const std::weak_ptr<Controls> &rhs)const {
          auto lptr = lhs.lock(), rptr = rhs.lock();
          return lptr < rptr;
      }
  };

  using ControlSet = std::set<std::weak_ptr<Controls>, WeakPtrCmp>;

  ControlSet commands;
  ControlSet to_remove;
  MainLoop& main_loop;
};

}

