<?php
/*
 * PHP version 5
 *
 * @copyright Copyright 2010, Cake. (http://trpgtools-onweb.sourceforge.jp/)
 * @category Model
 * @package  TRPG Data Bank
 * @version  beta
 * @author   Cake <cake_67@users.sourceforge.jp>
 * @license  http://www.opensource.org/licenses/mit-license.php The MIT License
 * @link     http://trpgtools-onweb.sourceforge.jp/
 */

class CharacterPicture extends AppModel {

	var $name = 'CharacterPicture';

	var $fields = array(
		'add' => array('user_id', 'character_id', 'public_flag'),
		'edit' => array('public_flag'),
		'image' => array(
			'user_id',
			'model',
			'foreign_key',
			'dirname',
			'basename',
			'checksum',
			'size',
			'group',
			'alternative',
			'file',
		),
		'escape' => array(
		),
	);

	var $validate = array(
		'public_flag' => array(
			'publicFlag' => array(
				'rule' => 'publicFlag',
				'allowEmpty' => true,
			),
		),
	);

	//The Associations below have been created with all possible keys, those that are not needed can be removed
	var $belongsTo = array(
		'User' => array(
			'className' => 'User',
			'foreignKey' => 'user_id',
			'conditions' => '',
			'fields' => '',
			'order' => ''
		),
		'Character' => array(
			'className' => 'Character',
			'foreignKey' => 'character_id',
			'conditions' => '',
			'fields' => array(
				'Character.id',
				'Character.name',
				'Character.public_flag',
				'Character.main_picture',
				'Character.full_length',
			),
			'order' => ''
		)
	);

	var $hasMany = array(
		'Attachment' => array(
			'className' => 'Media.AttachmentEx',
			'foreignKey' => 'foreign_key',
			'dependent' => true,
			'conditions' => array('Attachment.model' => 'CharacterPicture'),
			'fields' => array(
				'Attachment.id',
				'Attachment.user_id',
				'Attachment.foreign_key',
				'Attachment.dirname',
				'Attachment.basename',
				'Attachment.alternative',
				'Attachment.size',
				'Attachment.created',
			),
			'dependent' => true,
			'order' => '',
			'limit' => '',
			'offset' => '',
			'exclusive' => '',
			'finderQuery' => '',
			'counterQuery' => ''
		)
	);

	/* コールバックメソッド */
	function beforeSave($options = array())
	{
		if (isset($this->data['CharacterPicture'])) {
			// 登録者ID
			$this->data['CharacterPicture']['user_id'] = $_SESSION['Auth']['User']['id'];
		}
		return parent::beforeSave($options);
	}
	function afterSave($created) {
		$this->deleteCache4CharacterPicture($this->data['clearCache']['character_id']);
		$this->deleteCacheCharacterView($this->data['clearCache']['character_id'], true);

		return parent::afterSave($created);
	}
	function afterDelete() {
		$this->deleteCache4CharacterPicture($this->data['clearCache']['character_id']);

		$this->Character->deleteCache4Charcter();

		return parent::afterDelete();
	}
}
