<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

if (!function_exists('get_s3_instance'))
{
	function &get_s3_instance()
	{
		static $s3_instance;

		if (empty($s3_instance))
		{
			if (file_exists(FCPATH . 'common/third_party/aws/S3.php'))
			{
				require_once FCPATH . 'common/third_party/aws/S3.php';
				$s3_instance = new OBooksS3(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_REGION, AWS_BUCKET_NAME);
			}
			else
			{
				return false;
			}
		}

		return $s3_instance;
	}
}

if (!function_exists('upload_to_s3'))
{
	function upload_to_s3($from="", $to="")
	{
		if (!defined('USE_AWS_S3') || !USE_AWS_S3 || empty($from) || empty($to))
		{
			return false;
		}

		$s3	= get_s3_instance();
		if (!$s3)
		{
			return false;
		}

		$result = $s3->putObject($from, $to, OBooksS3::ACL_PRIVATE);

		if ($result)
		{
			return $result;
		}

		throw $s3->error;
		return false;
	}
}

if (!function_exists('delete_from_s3'))
{
	function delete_from_s3($file="")
	{
		if (!defined('USE_AWS_S3') || !USE_AWS_S3 || empty($file))
		{
			return false;
		}

		$s3	= get_s3_instance();
		if (!$s3)
		{
			return false;
		}

		return $s3->deleteObject($file);
	}
}

if (!function_exists('get_from_s3'))
{
	function get_from_s3($file="", $loc_file="")
	{
		if (!defined('USE_AWS_S3') || !USE_AWS_S3 || empty($file))
		{
			return false;
		}

		$s3	= get_s3_instance();
		if (!$s3)
		{
			return false;
		}
		$result = $s3->getObject($file, $loc_file);

		if (!empty($result))
		{
			return $result;
		}

		return false;
	}
}

