<?php

/**
 * Model for images.
 *
 * @package Brivium_Store
 */
class Brivium_Credits_Model_Image extends XenForo_Model
{
	/**
	 * Processes an image upload for a content.
	 *
	 * @param XenForo_Upload $upload The uploaded image.
	 * @param integer $contentId Content ID image belongs to
	 * @param array|false $permissions User's permissions. False to skip permission checks
	 *
	 * @return array Changed image fields
	 */
	public function uploadImage(XenForo_Upload $upload, $contentId, $permissions)
	{
		if (!$upload->isValid())
		{
			throw new XenForo_Exception($upload->getErrors(), true);
		}

		if (!$upload->isImage())
		{
			throw new XenForo_Exception(new XenForo_Phrase('uploaded_file_is_not_valid_image'), true);
		};

		$imageType = $upload->getImageInfoField('type');
		//prd($imageType);
		if (!in_array($imageType, array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG)))
		{
			throw new XenForo_Exception(new XenForo_Phrase('uploaded_file_is_not_valid_image'), true);
		}

		$baseTempFile = $upload->getTempFile();

		$width = $upload->getImageInfoField('width');
		$height = $upload->getImageInfoField('height');
		return $this->applyImage($contentId, $baseTempFile, $imageType, $width, $height, $permissions);
	}

	/**
	 * Applies the image file to the specified user.
	 *
	 * @param integer $contentId
	 * @param string $fileName
	 * @param constant|false $imageType Type of image (IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG)
	 * @param integer|false $width
	 * @param integer|false $height
	 * @param array|false $permissions
	 *
	 * @return array
	 */
	public function applyImage($contentId, $fileName, $imageType = false, $width = false, $height = false, $permissions = false)
	{
		
		if (!$imageType || !$width || !$height)
		{
			$imageInfo = getimagesize($fileName);
			if (!$imageInfo)
			{
				throw new XenForo_Exception('Non-image passed in to applyImage');
			}
			$width = $imageInfo[0];
			$height = $imageInfo[1];
			$imageType = $imageInfo[2];
		}
		
		if (!in_array($imageType, array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG)))
		{
			throw new XenForo_Exception('Invalid image type passed in to applyImage');
		}

		if (!XenForo_Image_Abstract::canResize($width, $height))
		{
			throw new XenForo_Exception(new XenForo_Phrase('uploaded_image_is_too_big'), true);
		}

		$outputFiles = array();
		$originalImageType = image_type_to_extension($imageType);
		
		$outputType = $imageType;
		
		$newTempFile = tempnam(XenForo_Helper_File::getTempDir(), 'xf');
		copy($fileName, $newTempFile); // no resize necessary, use the original
		$outputFiles = $newTempFile;
		
		
		$this->_writeImage($contentId, $originalImageType, $newTempFile);
		// done in 2 loops as multiple items may point to same file
		if ($newTempFile != $fileName)
		{
			@unlink($newTempFile);
		}
		
		$dwData = array(
			'image_type' => $originalImageType,
		);

		$dw = XenForo_DataWriter::create('Brivium_Credits_DataWriter_Currency');
		$dw->setExistingData($contentId);
		$dw->bulkSet($dwData);
		$dw->save();

		return $dwData;
	}

	

	/**
	 * Writes out an image.
	 *
	 * @param integer $contentId
	 * @param string $imageType
	 * @param string $tempFile Temporary image file. Will be moved.
	 *
	 * @return boolean
	 */
	protected function _writeImage($contentId, $imageType, $tempFile)
	{
		$filePath = $this->getImageFilePath($contentId, $imageType);
		$directory = dirname($filePath);

		if (XenForo_Helper_File::createDirectory($directory, true) && is_writable($directory))
		{
			if (file_exists($filePath))
			{
				unlink($filePath);
			}

			$success = rename($tempFile, $filePath);
			if ($success)
			{
				XenForo_Helper_File::makeWritableByFtpUser($filePath);
			}

			return $success;
		}
		else
		{
			return false;
		}
	}
	
	/**
	 * Get the file path to an image.
	 *
	 * @param integer $contentId
	 * @param string $imageType
	 *
	 * @return string
	 */
	public function getImageFilePath($contentId, $imageType)
	{
		return sprintf('%s/brcimages/currency/%s%s',
			XenForo_Helper_File::getExternalDataPath(),
			$contentId,
			$imageType
		);
	}

	/**
	 * Deletes a image.
	 *
	 * @param integer $contentId
	 * @param string $imageType
	 *
	 */
	public function deleteImage($contentId, $imageType)
	{
		$filePath = $this->getImageFilePath($contentId, $imageType);
		if (file_exists($filePath) && is_writable($filePath))
		{
			unlink($filePath);
		}
	}

}