<?php

/**
 * THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 *
 * @package fusionLib
 * @copyright Copyright (c) 2016 fusionLib. All rights reserved.
 * @link http://fusionlib.com
 */

/**
 * flLogHandlerSlack Class
 *
 * Log handler for Slack.
 *
 * @package fusionLib
 */
class flLogHandlerSlack implements flLogHandler {

	/**
	 * The client interface to log to.
	 *
	 * @var flHttpClient
	 */
	protected $client = null;

	/**
	 * The access token.
	 *
	 * @var string
	 */
	protected $token;

	/**
	 * The channel to log to.
	 *
	 * @var string
	 */
	protected $channel;

	/**
	 * Constructor.
	 *
	 * @param string $token The access token.
	 * @param string $channel The channel to log to..
	 */
	function __construct($token, $channel) {
		$this->token = $token;
		$this->channel = $channel;
	}

	/**
	 * Write a record to the log target.
	 *
	 * @param array $record The record to log.
	 */
	public function write($record) {

		// Connect if required
		if(!$this->client) {
			$this->client = new flHttpClient('https://slack.com/api/chat.postMessage');
		}

		$d = new stdClass();
		$d->pretext = is_string($record['message']) ? $record['message'] : json_encode($record['message'], JSON_PRETTY_PRINT);

		// Format
		$this->client->setPostData(array(
			'token' => $this->token,
			'channel' => $this->channel,
			'text' => (empty($record['channel']) ? '' : $record['channel'] . '.') . $record['level_name'],
			'attachments' => json_encode(array($d))
		))->sendRequest('post');
	}
}