<?php
/**
 * DeveloperSettings Controller
 *
 * @author Noriko Arai <arai@nii.ac.jp>
 * @author Shohei Nakajima <nakajimashouhei@gmail.com>
 * @link http://www.netcommons.org NetCommons Project
 * @license http://www.netcommons.org/license.txt NetCommons License
 * @copyright Copyright 2014, NetCommons Project
 */

App::uses('SystemManagerAppController', 'SystemManager.Controller');
App::uses('File', 'Utility');

/**
 * システム管理【開発者向け】
 *
 * @author Shohei Nakajima <nakajimashouhei@gmail.com>
 * @package NetCommons\SystemManager\Controller
 */
class DeveloperController extends SystemManagerAppController {

/**
 * application.ymlのプレフィックス(Unitテストで使用する)
 *
 * @return array
 */
	public $appYmlPrefix = '';

/**
 * use model
 *
 * @var array
 */
	public $uses = array(
		'SiteManager.SiteSetting',
	);

/**
 * edit
 *
 * @return void
 */
	public function edit() {
		//リクエストセット
		if ($this->request->is('post')) {
			//登録処理
			if (! $this->request->data['SiteSetting']['only_session']) {
				unset($this->request->data['SiteSetting']['only_session']);
				$this->Session->write('debug', null);

				//application.ymlに書き込み
				$conf = Spyc::YAMLLoad(APP . 'Config' . DS . 'application.yml');
				$conf['debug'] = (int)$this->request->data['SiteSetting']['debug']['0']['value'];

				$file = new File(APP . 'Config' . DS . $this->appYmlPrefix . 'application.yml', true);
				$file->write(Spyc::YAMLDump($conf));

				$this->SiteManager->saveData();

			} else {
				$this->SiteSetting->validateDeveloper($this->request->data);
				if (! $this->SiteSetting->validationErrors) {
						$this->Session->write(
							'debug', (int)$this->request->data['SiteSetting']['debug']['0']['value']
						);
						$this->NetCommons->setFlashNotification(__d('net_commons', 'Successfully saved.'), array(
							'class' => 'success',
						));
						$this->redirect($this->referer());
				} else {
					$this->NetCommons->handleValidationError($this->SiteSetting->validationErrors);
				}
			}

		} else {
			$this->request->data['SiteSetting'] = $this->SiteSetting->getSiteSettingForEdit(
				array('SiteSetting.key' => array(
					// * デバッグ出力
					'debug',
				)
			));
			$onlySession = $this->Session->read('debug');
			$this->request->data['SiteSetting']['only_session'] = isset($onlySession);
			if ($this->request->data['SiteSetting']['only_session']) {
				$this->request->data['SiteSetting']['debug']['0']['value'] = $onlySession;
			}
		}
	}
}
