<?php
/**
 * ConfigurationController class file.
 * @author Christoffer Niska <ChristofferNiska@gmail.com>
 * @copyright Copyright &copy; Christoffer Niska 2012-
 * @license http://www.opensource.org/licenses/bsd-license.php New BSD License
 * @package auth.controllers
 */

/**
 * Controller for assignment related actions.
 */
class ConfigurationController extends AuthController
{
	public function actionIndex()
	{	
	  $this->render('index');
	}
	
	public function actionImport()
	{	 

		
	  if(isset($_FILES['userfile']) && file_exists($_FILES['userfile']['tmp_name']))
	  {
	    $json = file_get_contents($_FILES['userfile']['tmp_name']);
	    $conf = json_decode($json);
	     
	    if($_POST['reset_db'] == 'yes')
	    {
	      AuthItem::model()->deleteAll();
	      AuthItemChild::model()->deleteAll();      
	    }

	    $totalItems = 0;
	    $totalItemsOk = 0;
	    $totalChilds = 0;
	    $totalChildsOk = 0;
	    foreach($conf->items as $item)
	    {
	      $totalItems++;
	      $attributes = (array) $item;
	      $auth = new AuthItem();
	      $auth->attributes = $attributes;
	      if($auth->insert())
	        $totalItemsOk++;
	    }
	  	     
	    foreach($conf->childs as $item)
	    {
	      $totalChilds++;
	      $attributes = (array) $item;
	      $auth = new AuthItemChild();
	      $auth->attributes = $attributes;	       
	      if($auth->insert())
	        $totalChildsOk++;
	    }
      user()->setFlash('notice', "Created $totalItemsOk auth items on $totalItems, Created $totalChildsOk childs on $totalChilds");
	  }
	  
	  $this->render('import');
	}
	
	public function actionExport()
	{
	
	  $conf = array();

	  $items = array();
	  foreach(AuthItem::getAll() as $item)
	    $items[] = $item->attributes;
	  $conf['items'] = $items;
	  
	  $childs = array();
	  foreach(AuthItemChild::getAll() as $item)
	    $childs[] = $item->attributes;
	  $conf['childs'] = $childs; 	  

	  $content = json_encode($conf);
	  $fileName = DateHelper::ensureObjectEx()->toFilesafeDateTimeString()."_EventServerGuiAuthConfig.json";
	  
	  header('Set-Cookie: fileDownload=true; path=/');
	  
	  app()->getRequest()->sendFile($fileName, $content, "application/json", true);
	}
	
	public function actionExportItemAndChilds($name)
	{
		$conf = array();
	
		$items = array();
		
		$item = AuthItem::model()->findItem($name);
		
		$items[] = $item->attributes;
		
		$conf['items'] = $items;
			 
		$childs = array();
		
		$childs = array();
		foreach($item->childLinks as $itemc)
			$childs[] = $itemc->attributes;
			
				
		  $conf['childs'] = $childs;
	
		  $content = json_encode($conf);
		  $fileName = $item->name."_EventServerGuiAuthConfig.json";
		   
		  header('Set-Cookie: fileDownload=true; path=/');
		   
		  app()->getRequest()->sendFile($fileName, $content, "application/json", true);
	}
	
}
