<?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
 */

/**
 * flLogHandlerLoggly Class
 *
 * Log handler for Loggly.
 *
 * @package fusionLib
 */
class flLogHandlerLoggly implements flLogHandler {

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

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

	/**
	 * Array of tags.
	 *
	 * @var array
	 */
	protected $tags;

	/**
	 * Constructor.
	 *
	 * @param string $token The access token.
	 * @param array $tags Array of tags to send with each message.
	 */
	function __construct($token, $tags = array()) {
		$this->token = $token;
		$this->tags = is_array($tags) ? $tags : array($tags);
	}

	/**
	 * 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://logs-01.loggly.com/inputs/1ae02f61-c8d6-4a79-bf71-b5480b6543f9/');
			$this->client->setContentType('application/json');

			if(count($this->tags))
				$this->client->addHeader('X-LOGGLY-TAG', implode(',', $this->tags));
		}

		// Format and send message
		$this->client->setPostData(json_encode($record))->sendRequest('post');
	}
}