<?php
/**
 * A class for logging information to a database.
 */
class log_writer_db extends log_filter
{
    /**
     * @var db_connection The db connection.
     */
    protected $connection;
    
    /**
     * @var string The database schema.
     * 
     * CREATE TABLE `log` (
     *   `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
     *   `timestamp` DATETIME NOT NULL,
     *   `priority` TINYINT NOT NULL,
     *   `message` VARCHAR(255) NOT NULL
     * );
     */
    protected $table, $timestamp, $priority, $message;
    
    ////////////////////////////////////////////////////////////////////////////
    // Construct and destruct functions.

    /**
     * @param integer (optional) $filter The priority filter.
     * @param string/db_connection (optional) $connection The db connection or
     * name.
     * @param string (optional) $table The table name.
     * @param string (optional) $timestamp The timestamp column name.
     * @param string (optional) $priority The priority column name.
     * @param string (optional) $message The message column name.
     */
    public function __construct($filter = log::DEBUG, $connection = 'default', $table = 'log', $timestamp = 'timestamp', $priority = 'priority', $message = 'message')
    {
        parent::__construct($filter);
        $this->connection = $connection;
        $this->table = $table;
        $this->timestamp = $timestamp;
        $this->priority = $priority;
        $this->message = $message;
    }

    ////////////////////////////////////////////////////////////////////////////
    // Overload functions.
    
    ////////////////////////////////////////////////////////////////////////////
    // Interface functions.
    
    ////////////////////////////////////////////////////////////////////////////
    // Internal functions.
    
    /**
     * Inserts a log message into a database.
     *
     * @param string $message The message.
     * @param integer $priority The priority.
     * @param string $timestamp The date.
     * @return log_writer_db A fluent interface.
     */
    protected function _write($message, $priority, $timestamp)
    {
        if (!$this->connection instanceof db_connection)
        {
            $this->connection = db::get($this->connection);
        }
        
        $this->connection->query()->insert($this->table)
                                  ->column($this->timestamp, $timestamp)
                                  ->column($this->priority, $priority)
                                  ->column($this->message, $message)
                                  ->execute();
        
        return $this;
    }
}
