<?php

/**
 * @file
 * The class for PoolParty Taxonomy Manager configuration.
 */

class PPTaxonomyManagerConfig {

  protected $id;
  protected $title;
  protected $connectionId;
  protected $projectId;
  protected $connection;
  protected $config;

  /**
   * Constructor of the PPTaxonomyManagerConfig class.
   *
   * @param int $config_id
   *   ID of the configuration set
   */
  public function __construct($config_id = 0) {
    // Load configuration set.
    $config = FALSE;
    if ((int) $config_id > 0) {
      $config = db_select('pp_taxonomy_manager', 'tm')
        ->fields('tm')
        ->condition('tmid', $config_id)
        ->execute()
        ->fetch();
    }

    if ($config) {
      $this->id = $config_id;
      $this->title = $config->title;
      $this->connectionId = $config->connection_id;
      $this->projectId = $config->project_id;
      $this->connection = SemanticConnector::getConnection('pp_server', $config->connection_id);

      // Add the config.
      $config_unserialized = unserialize($config->config);
      $complete_config = self::getDefaultConfig();
      if (is_array($config_unserialized) && !empty($config_unserialized)) {
        $complete_config = array_merge($complete_config, $config_unserialized);
      }
      $this->config = $complete_config;
    }
    else {
      $this->id = 0;
      $this->title = '';
      $this->connectionId = 0;
      $this->projectId = '';
      $this->connection = SemanticConnector::getConnection('pp_server', $this->connectionId);
      $this->config = self::getDefaultConfig();
    }
  }

  /**
   * Get the default config of a configuration set.
   *
   * @return array
   *   Config of the configuration set
   */
  public static function getDefaultConfig() {
    return array(
      'taxonomies' => array(),
      'root_level' => 'project',
    );
  }

  /**
   * Getter-function for the PoolParty Taxonomy Manager ID.
   *
   * @return int
   *   ID of the configuration set
   */
  public function getId() {
    return $this->id;
  }

  /**
   * Getter-function for the title.
   *
   * @return string
   *   Title of the configuration set
   */
  public function getTitle() {
    return $this->title;
  }

  /**
   * Setter-function for the title.
   *
   * @param string $title
   *   The title of the configuration.
   */
  public function setTitle($title) {
    if (is_string($title)) {
      $this->title = $title;
    }
  }

  /**
   * Getter-function for the Semantic Connector connection ID.
   *
   * @return int
   *   Semantic Connector connection ID of the configuration set
   */
  public function getConnectionId() {
    return $this->connectionId;
  }

  /**
   * Setter-function for the connection ID.
   *
   * @param int $id
   *   The Semantic Connector connection ID.
   */
  public function setConnectionId($id) {
    $this->connectionId = (int) $id;
  }

  /**
   * Getter-function for the project ID.
   *
   * @return string
   *   ID of the used PoolParty project.
   */
  public function getProjectId() {
    return $this->projectId;
  }

  /**
   * Setter-function for the project ID.
   *
   * @param string $id
   *   The ID of the used PoolParty project.
   */
  public function setProjectId($id) {
    if (is_string($id) || is_null($id)) {
      $this->projectId = $id;
    }
  }

  /**
   * Getter-function for the Semantic Connector connection object.
   *
   * @return SemanticConnectorConnection
   *   Semantic Connector connection object of the configuration set
   */
  public function getConnection() {
    return $this->connection;
  }

  /**
   * Getter-function for the configuration.
   *
   * @return array
   *   Config of the configuration set
   */
  public function getConfig() {
    return $this->config;
  }

  /**
   * Setter-function for the configuration.
   *
   * @param array $config
   *   The config of the configuration set.
   */
  public function setConfig($config) {
    if (is_array($config)) {
      $this->config = $config;
    }
  }

  /**
   * Updates an existing connection between a taxonomy and a PP concept scheme.
   *
   * @param int $vid
   *   The taxonomy ID.
   * @param string $scheme_uri
   *   The concept scheme URI.
   * @param array $languages
   *   An array of language mappings between Drupal and PoolParty project
   *   languages.
   * @param array $data_properties
   *   An array of SKOS properties to be fetched.
   */
  public function updateConnection($vid, $scheme_uri, $languages, $data_properties) {
    $this->addConnection($vid, $scheme_uri, $languages, $data_properties);
  }

  /**
   * Adds a new connection between a taxonomy and a PoolParty concept scheme.
   *
   * @param int $vid
   *   The taxonomy ID.
   * @param string $scheme_uri
   *   The concept scheme URI.
   * @param array $languages
   *   An array of language mappings between Drupal and PoolParty project
   *   languages.
   * @param array $data_properties
   *   An array of SKOS properties to be fetched.
   */
  public function addConnection($vid, $scheme_uri, $languages, $data_properties) {
    $this->config['taxonomies'][$vid] = $scheme_uri;
    $this->config['languages'][$vid] = $languages;
    $this->config['data_properties'][$vid] = $data_properties;
    $this->save();
  }

  /**
   * Deletes a connection between a taxonomy and a PoolParty concept scheme.
   *
   * @param int $vid
   *   The taxonomy ID.
   */
  public function deleteConnection($vid) {
    unset($this->config['taxonomies'][$vid]);
    unset($this->config['languages'][$vid]);
    unset($this->config['data_properties'][$vid]);
    $this->save();
  }

  /**
   * Saves the configuration data to the database.
   *
   * @return int
   *   The configuration ID.
   */
  public function save() {
    $fields = array(
      'title' => $this->title,
      'connection_id' => $this->connectionId,
      'project_id' => $this->projectId,
      'config' => serialize($this->config),
    );
    if ($this->id > 0) {
      db_update('pp_taxonomy_manager')
        ->fields($fields)
        ->condition('tmid', $this->id)
        ->execute();
    }
    else {
      $this->id = db_insert('pp_taxonomy_manager')
        ->fields($fields)
        ->execute();
    }

    return $this->id;
  }

  /**
   * Deletes the configuration from the database.
   */
  public function delete() {
    db_delete('pp_taxonomy_manager')
      ->condition('tmid', $this->id)
      ->execute();
  }

  /**
   * Get the last synchronization log of the taxonomy manager config.
   *
   * @param int $vid
   *   Optional; The vocabulary ID to filter by. Use 0 to not filter by a vid.
   *
   * @return array
   *   An associative array containing start time, end time, user ID and user
   *   name of the last log.
   */
  public function getLastLog($vid = 0) {
    $last_log_query = db_select('pp_taxonomy_manager_logs', 'l')
      ->fields('l', array('start_time', 'end_time', 'uid'));

    if ($vid != 0) {
      $last_log_query->condition('vid', $vid);
    }

    $last_log_query->join('users', 'u', 'l.uid = u.uid');
    $last_log_query->fields('u', array('name'));
    $last_log = $last_log_query->orderBy('start_time', 'DESC')
      ->range(0, 1)
      ->execute()
      ->fetchAssoc();

    return $last_log;
  }
}
