// src/python_cpu_policy.hh - Copyright 2005, 2006, University
//               of Padova, dept. of Pure and Applied
//               Mathematics
//
// This file is part of SGPEMv2.
//
// This 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.
//
// SGPEMv2 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 SGPEMv2. If not, see http://www.gnu.org/licenses/.


#ifndef PYTHON_CPU_POLICY_HH
#define PYTHON_CPU_POLICY_HH 1

#include "config.h"

#include <sgpemv2/cpu_policy.hh>
#include <sgpemv2/user_interrupt_exception.hh>
#include <sgpemv2/malformed_policy_exception.hh>

#include <Python.h>

#include <glibmm/thread.h>
#include <glibmm/ustring.h>

#include <iostream>

namespace sgpem
{
  /// \brief A specialization of abstract class Policy
  ///
  /// Implements the Policy abstract class specified in the backend component to allow 
  /// user-written Python policies to run.
  ///
  /// This class represents a policy written in Python. Its methods interact 
  /// with Python interpreter.
  /// See the documentation of class Policy for more detailed informations.
  ///
  /// Since both the methods get_name() and get_description() must be available before
  /// backend::Policy activation, then map them to the class name and the return of 
  /// the __doc__() method, respectively.
  /// That information can be obtained statically (without
  /// instantiating an object of that class).
  class PythonCPUPolicy;

  class PythonCPUPolicyManager;

  class SG_DLLEXPORT PythonCPUPolicy : public CPUPolicy
  {
  public:

    /// \brief Constructor taking the name of the policy.
    ///
    /// Constructor taking the name of the policy.
    /// Perform the first half of the two-staged construction
    ///
    /// A ::PythonPolicy object is instantiated as soon as its ::PythonPolicyManager 
    /// calls collect_policies(). In order to save memory, since only a small subset 
    /// of policies can be activated in a given time frame, this constructor only 
    /// takes care to determine the policy name and description, without actually 
    /// preparing a separate PyInterpreter and/or PyThreadState.
    /// @see activate().
    /// @throw an exception when the policy is malformed and therefore not usable.
    /// @param name the name of the policy
    PythonCPUPolicy(const char* name);

    /// \brief Standard virtual destructor
    ///
    virtual ~PythonCPUPolicy();

    /// \brief Configures the policy, asynchronously.
    ///
    /// Configures the policy, asynchronously. Calls the method \c async_configure
    /// Performs the following operations in this order:

    /// -# Erases the content of the PolicyParameters attribute
    /// -# Calls associated method async_configure() from the loaded 
    /// ::ScriptAdapter, which has been properly initialized from the activate() method
    /// -# Wait for the async call to return, calling wait_unlock()
    /// @throw an exception when the policy is malformed and therefore not usable,
    /// or when the policy is taking too long to terminate its work.
    /// @see ::CPUPolicy::configure().
    void configure();

    /// \brief Sorts the queue, asynchronously.
    ///
    /// Sorts the queue, asynchronously. Calls the method \c async_sort_queue.
    /// @throw an exception when the policy is malformed and therefore not usable,
    /// or when the policy is taking too long to terminate its work.
    /// @see ::CPUPolicy::sort_queue().
    void sort_queue() const;

    /// \brief Returns a textual description of the policy.
    ///
    /// Returns a textual description of this policy.
    /// Tries to get the result of calling __doc__() of the corresponding 
    /// Python-implemented Policy object, if available. Else, returns the empty string.
    /// @return long description of the policy.
    /// @see ::CPUPolicy::get_description().
    Glib::ustring get_description() const;

    /// \brief Returns a human-readable name of this policy.
    ///
    /// Returns a human-readable name of this policy.
    /// The name of the script file, stripped by its extension --
    /// typically, it's regexp(/.py(c?)/i)
    /// @return the name of this policy.
    /// @see ::CPUPolicy::get_name().
    Glib::ustring get_name() const;

    /// \brief Returns whether this policy is preemptive or not, asynchronously.
    ///
    /// Returns whether this policy is preemptive or not, asynchronously.
    /// Calls ScriptAdapter::async_is_preemptive(). Waits for an answer into wait_unlock()
    /// @throw an exception when the policy is malformed and therefore not usable,
    /// or when the policy is taking too long to terminate its work.
    /// @return \c TRUE if the policy is preemptive.
    /// @return \c FALSE if the policy is not preemptive.
    /// @see ::CPUPolicy::is_pre_emptive().
    bool is_pre_emptive() const;

    /// \brief Returns the lenght of the time slice, asynchronously.
    ///
    /// Returns the lenght of the time slice, asynchronously.
    /// Calls ScriptAdapter::async_get_timeslice(). Waits for an answer into wait_unlock()
    /// @throw an exception when the policy is malformed and therefore not usable,
    /// or when the policy is taking too long to terminate its work.
    /// @return the lenght of the time slice.
    /// @see ::CPUPolicy::get_time_slice().
    int get_time_slice() const;

    /// \brief Load the corresponding Python module and initialize a new Policy object (in Python).
    ///
    /// It will have its own PyThreadState and/or PyInterpreter.
    /// @throw an exception when the policy is malformed and therefore not usable,
    /// or when the policy is taking too long to terminate its work.
    /// @see ::CPUPolicy::activate().
    void activate();

    /// \brief Activates the policy.
    ///
    /// Cleanup operations to perform before another policy is loaded.
    /// @see ::CPUPolicy::deactivate().
    void deactivate();

  private:
    PythonCPUPolicy(const PythonCPUPolicy&);
    PythonCPUPolicy& operator=(const PythonCPUPolicy&);

    /// \brief Helps in implementing an asynchronous call to a method.
    ///
    /// Enters in a loop waiting for a ::ScriptAdapter method to return. If this 
    /// doesn't happen before a timeout expires, puts Policy and the Python 
    /// interpreter in a safe state and throws UserInterruptException.
    ///
    /// After an "async*()" call, the global Python interpreter lock has to be 
    /// released. This is necessary to let the Python threads to run. 
    /// After having waited for a specified amount of time (we're polling), 
    /// the lock is taken again, and we check if the thread has finished via 
    /// the mutex present in ::ScriptAdapter. If so, wait_unlock() terminates 
    /// successfully. Else it stays in its main loop.
    void wait_unlock() const;

    /// \brief Returns a brief description of a thrown exception. 
    /// Returns the description of the exception occurred.
    static std::string get_exception_information();

    static Glib::StaticRecMutex _mtx;
    
    PyObject* _upolicy_dict;
    PyObject* _adapter;
    Glib::ustring _name;
    Glib::ustring _description;
  };

}

#endif

