<?php
/*
 * PHP version 5
 *
 * @copyright Copyright 2010, Cake. (http://trpgtools-onweb.sourceforge.jp/)
 * @category Controller
 * @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 SystemsController extends AppController {

	var $name = 'Systems';
	var $helpers = array(
		'Select',
		'Profiledisp',
	);

	// listView用のpagenate設定
	var $paginate = array(
		'conditions' => array(
		),
		'fields' => array(
			'System.id',
			'System.name',
			'System.sort_order',
			'System.set_npc',
			'System.public_flag',
			'System.modified',
		),
		'recursive' => 1,
		'contain' => array(
			'Attachment',
			'Character',
		),
		'limit' => 20,
		'order' => array(
			'System.sort_order' => 'asc'
		),
	);

	var $disableTokenActions = array(
	);

	function beforeFilter() {

		parent::beforeFilter();

		// Cache
		$this->cacheAction = array(
			'index' => Configure::read('Cache.expireLong'),
			'view' => Configure::read('Cache.expire'),
		);

		// 認証なしアクセス可
		$this->AuthPlus->allow('index');
		$this->AuthPlus->allow('view');
	}

	function beforeRender()
	{
		parent::beforeRender();

			$this->set_public_flag4view();
	}


	function index() {
		// SingleSystem
		if ($this->site_configs['System.singleSystem']['value']) {
			$this->Session->setFlash(__('Invalid URL.', true));
			$this->redirect(array('controller'=>'users', 'action'=>'index'));
		}

		$this->paginate['conditions']['public_flag'] = 1;
		$this->System->hasMany['Character']['limit'] = 8;
		$this->_index(false);
	}

	function view($id = null) {
		$this->System->hasMany['Character']['limit'] = 15;
		$this->_view($id);
	}

	function admin_index() {
		unset($this->System->hasMany['Character']['conditions']['Character.public_flag']);
		$this->_index(true);
	}

	function admin_view($id = null) {
		$this->System->hasMany['Character']['limit'] = 30;
		unset($this->System->hasMany['CharacterSheet']['conditions']['CharacterSheet.public_flag']);
		unset($this->System->hasMany['Character']['conditions']['Character.public_flag']);
		$this->_view($id);
	}

	function admin_add() {
		if (!empty($this->data)) {
			if (empty($this->data['Attachment'][0]['file']['tmp_name'])) {
				unset($this->data['Attachment']);
			}

			$this->System->create();
			if ($this->System->saveAll($this->data, array('fieldList' => array_merge($this->System->fields['add'], $this->System->fields['image'])))) {
				$this->Session->setFlash(sprintf(__('%s has been saved', true), $this->data['System']['name']));
				$this->redirect(array('action'=>'view', $this->System->id));
			} else {
				$this->Session->setFlash(__('The data could not be saved. Please, try again.', true));
			}
		}

		$this->set('title_for_layout', " - ". __('Add New System', true));
	}

	function admin_edit($id = null) {
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid System', true));
			$this->redirect(array('action'=>'index'));
		}

		$system = $this->System->find('first', array(
			'conditions' => array('System.id' => $id),
			'fields' => '',
			'recursive' => 1,
			'contain' => array(
			 	'Attachment',
			),
		));
		$system = $this->_restore_html_system($system, true);

		if (!empty($this->data)) {
			$this->data['System']['id'] = $id;

			if ($this->System->saveAll($this->data, array('fieldList' => array_merge($this->System->fields['edit'], $this->System->fields['image'])))) {
				$this->Session->setFlash(sprintf(__('%s has been saved', true), $this->data['System']['name']));

				if ($this->data['System']['public_flag'] != 1) {
					$this->System->Character->updateAll(array('Character.public_flag' => "2"), array('Character.system_id' => $id));
				}

				$this->redirect(array('action'=>'view', $id));
			} else {
				$this->Session->setFlash(__('The data could not be saved. Please, try again.', true));
				$this->data['System']['id'] = $id;
				if (isset($this->data['Attachment'][1])) {
					list($alternative, $delete) = array($this->data['Attachment'][1]['alternative'], $this->data['Attachment'][1]['delete']);
				}
				$this->data['Attachment'] = $system['Attachment'];
			if (isset($alternative)) {
					$this->data['Attachment'][0]['alternative'] = $alternative;
					$this->data['Attachment'][0]['delete'] = $delete;
				}

			}
		}
		if (empty($this->data)) {
			$this->data = $system;
		}

		$this->set('title_for_layout', " - ". __('Edit System', true));
	}

	function admin_edit_all() {
		if (!isset($this->data['System'])) {
			$this->Session->setFlash(__('Invalid Data.', true));
			$this->redirect(array('controller' => 'systems', 'action'=>'admin_index'));
		}

		$error = false;
		foreach ($this->data['System'] as $id => $v) {
			if ($id == '__Token') {
				continue;
			}

			$system = $this->System->find('first', array(
				'conditions' => array(
					'System.id' => $id,
				),
				'contain' => array(
				),
				'recursive' => -1,
			));

			if (empty($system)) {
				$this->Session->setFlash(__('Invalid id for System', true));
				$error = true;
				break;
			}

			$data['System'] = array(
				'sort_order' => $v['sort_order'],
			);

			$this->System->id = $id;
			$this->System->set($data);
			if ($this->System->validates()) {
				if ($this->System->save($data, array('fieldList' => $this->System->fields['edit_all']))) {
				} else {
					$this->Session->setFlash(__('Some data could not be saved. Please, try again.', true));
					$error = true;
					break;
				}
			} else {
				$validate_errors = $this->System->invalidFields();
				$this->Session->setFlash(array_pop($validate_errors));
				$error = true;
				break;
			}
		}

		if (!$error) {
			$this->Session->setFlash(sprintf(__('%s has been saved', true), __('Order', true)));
		}

		$this->redirect(array('controller' => 'systems', 'action'=>'admin_index'));

	}


	function admin_delete($id = null) {
		// SingleSystem
		if ($this->site_configs['System.singleSystem']['value']) {
			$this->Session->setFlash(__('Invalid URL.', true));
			$this->redirect(array('controller'=>'site_configs', 'action'=>'admin_edit'));
		}

		if (!$id) {
			$this->Session->setFlash(__('Invalid id for System', true));
			$this->redirect(array('action'=>'index'));
		}
		if (isset($this->data['System']['confirm']) && $this->data['System']['confirm'] == 'yes') {
			if ($this->System->delete($id)) {
				$this->Session->setFlash(__('System deleted', true));
				$this->redirect(array('action'=>'index'));
			}
		}

		$this->set('title_for_layout', " - ". __('Delete System', true));

		$this->admin_view($id);
	}

	/* 共通メソッド */
	function _index($isAdmin = false)
	{
		$systems = $this->paginate();

		if (!empty($systems)) {
			$sort_order = array();
			foreach ($systems as $k => $v) {
				$systems[$k] = $this->_restore_html_system($v);
				// 全キャラクター数取得
				if (empty($v['Character'])) {
					$systems[$k]['System']['character_num'] = 0;
					continue;
				}

				$systems[$k]['System']['character_num'] = $this->System->Character->find('count', array(
					'conditions' => array_merge($this->System->hasMany['Character']['conditions'],
						array('Character.system_id' => $v['System']['id'])),
					'recursive' => -1,
				));
			}

			$systems = $this->HtmlEscape->nl_unescape($systems);
		}

		$this->set('systems', $systems);

		$this->set('title_for_layout', " - ". __('List of All Systems', true));
	}

	function _view($id = null, $conditions = array())
	{
		if (!$id) {
			$this->Session->setFlash(__('Invalid System.', true));
			$this->redirect(array('action'=>'index'));
		}

		// 抽出
		$conditions['System.id'] = $id;
		if ($this->isAdmin) {
			$this->System->hasMany['Profile']['fields'] = '';
			$contain = array(
				'Character',
				'CharacterSheet',
				'Profile' => array(
					'ProfileSelect',
					'ProfileTable' => array(
						'ProfileTableStatic',
					),
					'DefaultProfile',
				),
				'Attachment',
			);
			$recursive = 3;
		} else {
			$contain = array(
				'Character',
				'CharacterSheet',
				'Attachment',
			);
			$recursive = 1;
		}

		$system = $this->System->find('first', array(
			'conditions' => $conditions,
			'contain' => $contain,
			'recursive' => $recursive,
		));

		if (!isset($system['System']) || empty($system['System'])) {
			$this->Session->setFlash(__('No System.', true));
			$this->redirect(array('action'=>'index'));
		}
		$system = $this->_restore_html_system($system, true);
		if (isset($system['Profile'])) {
			foreach ($system['Profile'] as $k => $v) {
				if (!empty($v)) {
					$system['Profile'][$k] = $this->__restore_html_profile($v);
				}
			}
		}

		// 全キャラクター数取得
		if (empty($system['Character'])) {
			$system['System']['character_num'] = 0;
		}

		$system['System']['character_num'] = $this->System->Character->find('count', array(
			'conditions' => array_merge($this->System->hasMany['Character']['conditions'],
				array('Character.system_id' => $system['System']['id'])),
			'recursive' => -1,
		));

		$this->set('system', $this->HtmlEscape->nl2br_escaped($system));
		$this->set('profile_types', CorePlus::get_profile_types());

		$this->set('title_for_layout', " - ". $system['System']['name']);
	}

}
