/*
  Glaurung, a UCI chess playing engine.
  Copyright (C) 2004-2007 Tord Romstad

  Glaurung 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.
  
  Glaurung 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/>.
*/


////
//// Includes
////

#include <cstdarg>
#include <sstream>
#include <vector>

#include "misc.h"
#include "thread.h"
#include "ucioption.h"


////
//// Variables
////

bool Chess960 = false;


////
//// Local definitions
////

namespace {

  ///
  /// Types
  ///

  enum UCIOptionType {
    SPIN, COMBO, CHECK, STRING, BUTTON
  };

 
  class UCIOption {

  public:
    UCIOption(const std::string& aName, const std::string& aDefaultValue,
              UCIOptionType aType, int min, int max, ...);
    void print() const;
    const std::string get_name() const;
    const std::string get_value() const;
    void set_value(const std::string& newValue);

  private:
    std::string name;
    std::string defaultValue;
    std::string currentValue;
    UCIOptionType type;
    int minValue, maxValue;
    std::vector <std::string> comboValues;

  };


  ///
  /// Variables
  ///

  std::vector <UCIOption> Options;

  ///
  /// Functions
  ///

  UCIOption* option_with_name(const std::string& optionName);

}


////
//// Functions
////

/// init_uci_options() creates all the UCI options and adds them to the
/// array named 'Options'.  It is called during program initialization.

void init_uci_options() {
  Options.push_back(UCIOption("Use Search Log", "false", CHECK, 0, 0));
  Options.push_back(UCIOption("Search Log Filename", "SearchLog.txt",
                              STRING, 0, 0));
  Options.push_back(UCIOption("Book File", "book.bin", STRING, 0, 0));
  Options.push_back(UCIOption("Check Extension (PV nodes)", "2",
                              SPIN, 0, 2));
  Options.push_back(UCIOption("Check Extension (non-PV nodes)", "2",
                              SPIN, 0, 2));
  Options.push_back(UCIOption("Single Reply Extension (PV nodes)", "1",
                              SPIN, 0, 2));
  Options.push_back(UCIOption("Single Reply Extension (non-PV nodes)", "1",
                              SPIN, 0, 2));
  Options.push_back(UCIOption("Pawn Push to 7th Extension (PV nodes)", "1",
                              SPIN, 0, 2));
  Options.push_back(UCIOption("Pawn Push to 7th Extension (non-PV nodes)", "1",
                              SPIN, 0, 2));
  Options.push_back(UCIOption("Recapture Extension (PV nodes)", "2",
                              SPIN, 0, 2));
  Options.push_back(UCIOption("Pawn Endgame Extension (PV nodes)", "2",
                              SPIN, 0, 2));
  Options.push_back(UCIOption("Pawn Endgame Extension (non-PV nodes)", "2",
                              SPIN, 0, 2));
  Options.push_back(UCIOption("Late Move Reductions", "true", CHECK, 0, 0));
  Options.push_back(UCIOption("Threat Depth", "3", SPIN, 0, 100));
  Options.push_back(UCIOption("Selectivity", "6", SPIN, 0, 10));
  Options.push_back(UCIOption("Futility Pruning (Main Search)", "true",
                              CHECK, 0, 0));
  Options.push_back(UCIOption("Futility Pruning (Quiescence Search)", "true",
                              CHECK, 0, 0));
  Options.push_back(UCIOption("Futility Margin 0", "50", SPIN, 0, 1000));
  Options.push_back(UCIOption("Futility Margin 1", "100", SPIN, 0, 1000));
  Options.push_back(UCIOption("Futility Margin 2", "300", SPIN, 0, 1000));
  Options.push_back(UCIOption("Maximum Razoring Depth", "3", SPIN, 0, 4));
  Options.push_back(UCIOption("Razoring Margin", "300", SPIN, 150, 600));
  Options.push_back(UCIOption("Minimum Split Depth", "4", SPIN, 4, 7));
  Options.push_back(UCIOption("Maximum Number of Threads per Split Point",
                              "8", SPIN, 4, 8));
  Options.push_back(UCIOption("Threads", int_to_string(cpu_count()),
			      SPIN, 1, THREAD_MAX));
  Options.push_back(UCIOption("Hash", "32", SPIN, 4, 1024));
  Options.push_back(UCIOption("Clear Hash", "false", BUTTON, 0, 0));
  Options.push_back(UCIOption("Ponder", "true", CHECK, 0, 0));
  Options.push_back(UCIOption("OwnBook", "true", CHECK, 0, 0));
  Options.push_back(UCIOption("MultiPV", "1", SPIN, 1, 500));
  Options.push_back(UCIOption("UCI_ShowCurrLine", "false", CHECK, 0, 0));
  Options.push_back(UCIOption("UCI_Chess960", "false", CHECK, 0, 0));
  Options.push_back(UCIOption("UCI_EngineAbout", 
                              engine_name() + ".  " +
                              "Copyright (C) 2004-2007 Tord Romstad.  " +
                              "Glaurung is free software, and you are welcome to redistribute it under certain conditions; see the file Copying.txt for details.",
                              STRING, 0, 0));
}


/// print_uci_options() prints all the UCI options to the standard output,
/// in the format defined by the UCI protocol.

void print_uci_options() {
  for(unsigned i = 0; i < Options.size(); i++)
    Options.at(i).print();
}


/// get_option_value_bool() returns the current value of a UCI parameter of
/// type "check".

bool get_option_value_bool(const std::string& optionName) {
  UCIOption* u = option_with_name(optionName);
  if(u != NULL && u->get_value() == "true")
    return true;
  else
    return false;
}


/// get_option_value_int() returns the value of a UCI parameter as an integer.
/// Normally, this function will be used for a parameter of type "spin", but
/// it could also be used with a "combo" parameter, where all the available
/// values are integers.

int get_option_value_int(const std::string& optionName) {
  UCIOption* u = option_with_name(optionName);
  std::string value = u->get_value();
  std::istringstream i(value);
  int intValue;

  if(i >> intValue)
    return intValue;

  return 0;
}


/// get_option_value_string() returns the current value of a UCI parameter as
/// a string.  It is used with parameters of type "combo" and "string".

const std::string get_option_value_string(const std::string& optionName) {
  UCIOption* u = option_with_name(optionName);
  return u->get_value();
}


/// button_was_pressed() tests whether a UCI parameter of type "button" has
/// been selected since the last time the function was called.

bool button_was_pressed(const std::string& buttonName) {
  if(get_option_value_bool(buttonName)) {
    set_option_value(buttonName, "false");
    return true;
  }
  else
    return false;
}


/// set_option_value() inserts a new value for a UCI parameter.  Note that
/// the function does not check that the new value is legal for the given
/// parameter:  This is assumed to be the responsibility of the GUI.

void set_option_value(const std::string& optionName,
                      const std::string& newValue) {
  UCIOption* u = option_with_name(optionName);

  if(u != NULL)
    u->set_value(newValue);
  else
    std::cout << "No such option: " << optionName << std::endl;
}


/// push_button() is used to tell the engine that a UCI parameter of type
/// "button" has been selected:

void push_button(const std::string& buttonName) {
  set_option_value(buttonName, "true");
}


namespace {

  // Constructor for UCIOption class
  
  UCIOption::UCIOption(const std::string& aName, 
                       const std::string& aDefaultValue,
                       UCIOptionType aType, int min, int max, ...) {
    name.insert(0, aName);
    defaultValue.insert(0, aDefaultValue);
    currentValue.insert(0, aDefaultValue);
    minValue = min; 
    maxValue = max;
    type = aType;

    if(type == COMBO) {
      va_list arglist;
      char* str;
      va_start(arglist, max);
      do {
        str = va_arg(arglist, char *);
        if(str != NULL) 
          comboValues.push_back(std::string(str));
      } while(str != NULL);
      va_end(arglist);
    }
  }


  // UCIOption::print() prints the UCI option to the standard output, using
  // the format described in the UCI protocol.
  
  void UCIOption::print() const {
    const std::string optionTypeName[] = {
      "spin", "combo", "check", "string", "button"
    };
    std::cout << "option name " << name << " type " << optionTypeName[type];

    if(type != BUTTON) {
      std::cout << " default " << defaultValue;

      if(type == SPIN)
        std::cout << " min " << minValue << " max " << maxValue;
      else if(type == COMBO)
        for(unsigned i = 0; i < comboValues.size(); i++)
          std::cout << " var " << comboValues.at(i);
    }

    std::cout << std::endl;
  }


  // UCIOption()::get_name() and UCIOption::get_value() are used to
  // extract the name and the current value of the option.
  
  const std::string UCIOption::get_name() const {
    return name;
  }

  const std::string UCIOption::get_value() const {
    return currentValue;
  }


  // UCIOption::set_value() replaces the current value of the UCI option
  // with the value of the parameter 'newValue'.  The function does not
  // verify that the new value is legal.
  
  void UCIOption::set_value(const std::string& newValue) {
    currentValue.clear();
    currentValue.insert(0, newValue);
  }


  // UCIOption::option_with_name() tries to find a UCI option with a given
  // name.  It returns a pointer to the UCI option or the null pointer,
  // depending on whether an option with the given name exists.
  
  UCIOption* option_with_name(const std::string& optionName) {
    for(unsigned i = 0; i < Options.size(); i++)
      if(Options.at(i).get_name() == optionName)
        return &Options.at(i);
    return NULL;
  }

}
