<?
class FileController extends MainController implements ControllerInterface
{
	const AVATAR_DEST_DIR = '/upload/File';
	const AVATAR_TEMP_DIR = '/upload/temp';
	const CROPPER_BIG_PHOTO_MAX_WIDTH = 800;
	const CROPPER_BIG_PHOTO_MAX_HEIGHT = 800;
	const PHOTO_WIDTH = 283;
	const PHOTO_HEIGHT = 400;

	const IMAGE_MINI_WIDTH = 283;
	const IMAGE_MINI_HEIGHT = 400;
	const IMAGE_NORMAL_WIDTH = 283;
	const IMAGE_NORMAL_HEIGHT = 400;



	public function IndexAction($param){


		$dalData = MfFileDAL::GetDalDataObj();
		$dalData->setCondition(array());
		$dalData->setLimit(10);
		$dalData->setSortBy('weight');


		$arrayFile = MfFileDAL::GetResult($dalData);
		//Utils::ArrayDisplay($arrayFile);

	}
	public function IndexStructureAction($param){


		$lang = SessionProxy::GetValue('lang');
		$dalData = MfFileDAL::GetDalDataObj();
		$dalData->setCondition(array('lang' => $lang));
		$dalData->setSortBy('weight');


		$arrayFile = MfFileDAL::GetResult($dalData);
		$this->smarty->assign('arrayObj', $arrayFile);
		//Utils::ArrayDisplay($arrayFile);

	}

	public function EditStructureAction($param) {
		$lang = SessionProxy::GetValue('lang');
		$dalData = MfFileDAL::GetDalDataObj();
		$dalData->setCondition(array('lang' => $lang));
		$dalData->setSortBy('weight');


		$arrayFile = MfFileDAL::GetResult($dalData);
		$this->smarty->assign('arrayObj', $arrayFile);
	}

	/**
	 * Akcja dodawania 
	 *
	 * @param <type> $param
	 */
	public function AddAction($param) {



		$lang = SessionProxy::GetValue('lang');
		$idStructure = SessionProxy::GetValue('idStructure');
		if (!$idStructure) {
			$this->AddRedirect(Router::GenerateUrl('IndexStructure', array('Structure' => 'Index')), 0);
		}
		$this->smarty->assign('idStructure', $idStructure);
		//$idCategory = SessionProxy::GetValue('idCategory');
		$idCategory = $idStructure;
		$arrayFileType = Utils::GetArrayList('mf_file_type', 'id_mf_file_type','name');
		$this->smarty->assign('arrayFileType', $arrayFileType);

		$objFile = MfFileDAL::GetEmptyObj();


		if(Request::IsPost()) {
			$out = array();
			$validator  = new Validator(Request::GetAllPost());
			$data = Request::GetAllPost();

			$validator->IsEmpty('title', 'Pole nazwa musi zostać wypełnione.');
			//$validator->IsDate('datepublication', 'Pole data publikacji musi zostać wypełnione.');
			//$validator->IsEmpty('description', 'Pole opis musi zostać wypełnione.');
			$out = $validator->GetErrorList();

			$publication = Request::Get('publication');
			$publication ? $publication = 1 : $publication = '0';
			//$data['timepublication'] = $data['timepublication'] ?  $data['timepublication'] : '00';

			$objFileDescription = $objFile->GetDescriptionObj();

			$objFile->SetDate(Utils::GetNowDate());
			//$objFile->SetDatePublication($data['datepublication']." ".$data['timepublication'].":00:00");
			$objFile->SetDatePublication(Utils::GetNowDate());
			$objFile->SetWeight($data['weight']);
			$objFile->SetPublication($publication);
			$objFile->SetType($data['file_type']);
			$objFile->SetIdStructure($idCategory);
			$objFile->SetDateUpdate(Utils::GetNowDate());
			$objFile->SetAddDate(Utils::GetNowDate());
			$objFile->SetEditDate(Utils::GetNowDate());

			$objFileDescription->SetLang($lang);
			$objFileDescription->SetDescription($data['description']);
			$objFileDescription->SetTitle($data['title']);
			$objFileDescription->SetPublication($publication);

			if(empty($out)) {


				if($_FILES['filename']['tmp_name']){

					$destName = Utils::TextToUrl($_FILES['filename']['name']);
					if(file_exists(PATH_STATIC_CONTENT.'upload/File/'.$destName)) {
						$destName = '1_'.$destName;
					}

					move_uploaded_file($_FILES['filename']['tmp_name'], PATH_STATIC_CONTENT.'upload/File/'.$destName);
					umask(0000);
					@chmod(PATH_STATIC_CONTENT.'upload/File/'.$destName, 0777);
					$objFile->SetName($destName);
				}
				
				
				if($_FILES['photoname']['tmp_name']){

					$photoSize = getimagesize($_FILES['photoname']['tmp_name']);
					$photoProp = $photoSize[0] / $photoSize[1];

					$photoWidth = $photoSize[0];
					$photoHeight = $photoSize[1];

					if ($photoWidth > self::CROPPER_BIG_PHOTO_MAX_WIDTH) {
						$photoHeight = self::CROPPER_BIG_PHOTO_MAX_WIDTH / $photoProp;
						$photoWidth = self::CROPPER_BIG_PHOTO_MAX_WIDTH;
					}

					if ($photoHeight > self::CROPPER_BIG_PHOTO_MAX_HEIGHT) {
						$photoWidth = self::CROPPER_BIG_PHOTO_MAX_HEIGHT * $photoProp;
						$photoHeight = self::CROPPER_BIG_PHOTO_MAX_HEIGHT;
					}

					$photoFile = PhotoDAL::SimplePhotoUpload($_FILES['photoname'], self::AVATAR_TEMP_DIR . DIRECTORY_SEPARATOR , $photoWidth, $photoHeight, 100);



					$destName = md5('photo' . microtime());
					if(file_exists(PATH_STATIC_CONTENT.'upload/File/'.$destName.'.jpg'))
					unlink(PATH_STATIC_CONTENT.'upload/File/'.$destName.'.jpg');


					$propW = $photoWidth/self::IMAGE_NORMAL_WIDTH;
					$propH = $photoHeight/self::IMAGE_NORMAL_HEIGHT;

					if ($propW > $propH) {
						$prop = $propH;
					} else {
						$prop = $propW;
					}
					
					
					// maks szerokość
					//$photo = PhotoDAL::SaveTempFile($photoFile, $destName, '/upload/File', 0, 0, $photoWidth, $photoHeight, self::IMAGE_NORMAL_WIDTH,  $photoWidth/$prop);
					// maks wysokość
					//$photo = PhotoDAL::SaveTempFile($photoFile, $destName, '/upload/File', 0, 0, $photoWidth, $photoHeight, $photoHeight/$prop, self::IMAGE_NORMAL_HEIGHT);
					$photo = PhotoDAL::SaveTempFile($photoFile, $destName, '/upload/File', 0, 0, self::IMAGE_NORMAL_WIDTH*$prop, self::IMAGE_NORMAL_HEIGHT*$prop, self::IMAGE_NORMAL_WIDTH, self::IMAGE_NORMAL_HEIGHT);
					
					
//					Utils::ArrayDisplay('$prop: '.$prop);
//					Utils::ArrayDisplay('$propW: '.$propW);
//					Utils::ArrayDisplay('$propH: '.$propH);
//					Utils::ArrayDisplay('$photoHeight: '.$photoHeight);
//					Utils::ArrayDisplay('$photoWidth: '.$photoWidth);
///					Utils::ArrayDisplay('$photoHeight/$prop: '.$photoWidth/$prop);
//					Utils::ArrayDisplay('self::IMAGE_NORMAL_HEIGHT: '.self::IMAGE_NORMAL_HEIGHT);
					
					
					//Utils::ArrayDisplay('foto: '.$photo);
					$objPhoto = new Picture();
					$objPhoto->SetLink($photo);
					$objPhoto->SetWeight(1);
					$objPhoto->SetPublication(1);
					$idPhoto = PictureDAL::Insert($objPhoto);
					$objFile->SetIdPicture($idPhoto);
					$destName = md5('photo' . microtime());

					$propW = $photoWidth/self::IMAGE_MINI_WIDTH;
					$propH = $photoHeight/self::IMAGE_MINI_HEIGHT;

					if ($propW > $propH) {
						$prop = $propH;
					} else {
						$prop = $propW;
					}
					$photoMini = PhotoDAL::SaveTempFile($photoFile, $destName, '/upload/File', 0, 0, self::IMAGE_MINI_WIDTH*$prop, self::IMAGE_MINI_HEIGHT*$prop, self::IMAGE_MINI_WIDTH, self::IMAGE_MINI_HEIGHT);
					//Utils::ArrayDisplay('fotoMini: '.$photoMini);
					$objPhoto = new Picture();
					$objPhoto->SetLink($photoMini);
					$objPhoto->SetWeight(1);
					$objPhoto->SetPublication(1);
					$idPhoto = PictureDAL::Insert($objPhoto);
					$objFile->SetIdPictureMini($idPhoto);
				}
				if (isset($data['deletePhoto'])) {
					$objFile->SetIdPictureMini(0);
					$objFile->SetIdPicture(0);
				}

				$iid = MfFileDAL::Save($objFile);
				$objFileDescription->SetIdMfFile($iid);

				MfFileDescriptionDAL::Save($objFileDescription);

				$this->smarty->assign('iid', $iid);
				//$this->AddRedirect(Router::GenerateUrl('indexFile', array('File'=> 'Index')), 0);
				$this->AddRedirect(Router::GenerateUrl('editStructure', array('id' => $idStructure)), 0);

			}	else {
				//$this->content=$this->FormatAjaxOutput($out, $param);
				//Utils::ArrayDisplay($out);

				$objFile->SetFileDescriptionObj($objFileDescription);
				$this->smarty->assign('objFile',$objFile);
				$datePublished = explode(" ",$objFile->GetDatePublication());

				$this->smarty->assign("datePublished", $datePublished[0]);
				$this->smarty->assign("timePublished", $datePublished[1]);

				foreach ($out as $item) {
					$error[$item['field']] = $item['msg'];
				}
				$this->smarty->assign('error',$error);

			}
		}
	}


	/**
	 * Akcja dodawania 
	 *
	 * @param <type> $param
	 */
	public function EditAction($param) {

		//Utils::ArrayDisplay($_POST);

		$lang = SessionProxy::GetValue('lang');
		$idStructure = SessionProxy::GetValue('idStructure');
		$this->smarty->assign('idStructure', $idStructure);
		//$idCategory = SessionProxy::GetValue('idCategory');
		$idCategory = $idStructure;
		//$arrayFileType = Utils::GetArrayList('mf_file_type', 'name', $lang);
		//$this->smarty->assign('arrayFileType', $arrayFileType);

		//$objFile = MfFileDAL::GetEmptyObj();
		$objFile = MfFileDAL::GetById($param['idFile'], $lang);


		if(Request::IsPost()) {
			$out = array();
			$validator  = new Validator(Request::GetAllPost());
			$data = Request::GetAllPost();

			$validator->IsEmpty('title', 'Pole nazwa musi zostać wypełnione.');
			//$validator->IsDate('datepublication', 'Pole data publikacji musi zostać wypełnione.');
			//$validator->IsEmpty('description', 'Pole opis musi zostać wypełnione.');
			$out = $validator->GetErrorList();

			$publication = Request::Get('publication');
			$publication ? $publication = 1 : $publication = '0';

			$objFileDescription = $objFile->GetDescriptionObj();

			$objFile->SetDate(Utils::GetNowDate());
			//$objFile->SetDatePublication($data['datepublication']." ".$data['timepublication'].":00:00");
			$objFile->SetDatePublication(Utils::GetNowDate());
			$objFile->SetWeight($data['weight']);
			$objFile->SetPublication($publication);
			$objFile->SetIdStructure($idCategory);
			$objFile->SetType($data['file_type']);
			$objFile->SetDateUpdate(Utils::GetNowDate());
			$objFile->SetAddDate(Utils::GetNowDate());
			$objFile->SetEditDate(Utils::GetNowDate());
			//Utils::ArrayDisplay($objFile);
			$objFileDescription->SetLang($lang);
			$objFileDescription->SetDescription($data['description']);
			$objFileDescription->SetTitle($data['title']);
			$objFileDescription->SetPublication($publication);

			if(empty($out)) {


				if($_FILES['filename']['tmp_name']){

					if (file_exists($objFile->GetNamePath())) {
						unlink($objFile->GetNamePath());
					}

					$destName = Utils::TextToUrl($_FILES['filename']['name']);
					if(file_exists(PATH_STATIC_CONTENT.'upload/File/'.$destName)) {
						$destName = '1_'.$destName;
					}

					move_uploaded_file($_FILES['filename']['tmp_name'], PATH_STATIC_CONTENT.'upload/File/'.$destName);
					umask(0000);
					@chmod(PATH_STATIC_CONTENT.'upload/File/'.$destName, 0777);
					$objFile->SetName($destName);
				}
				
				
				
				//=obrazki na listę============================================================================================================================================================

				if($_FILES['photoname']['tmp_name']) {

					$photoSize = getimagesize($_FILES['photoname']['tmp_name']);
					$photoProp = $photoSize[0] / $photoSize[1];

					$photoWidth = $photoSize[0];
					$photoHeight = $photoSize[1];

					if ($photoWidth > self::CROPPER_BIG_PHOTO_MAX_WIDTH) {
						$photoHeight = self::CROPPER_BIG_PHOTO_MAX_WIDTH / $photoProp;
						$photoWidth = self::CROPPER_BIG_PHOTO_MAX_WIDTH;
					}

					if ($photoHeight > self::CROPPER_BIG_PHOTO_MAX_HEIGHT) {
						$photoWidth = self::CROPPER_BIG_PHOTO_MAX_HEIGHT * $photoProp;
						$photoHeight = self::CROPPER_BIG_PHOTO_MAX_HEIGHT;
					}

					$photoFile = PhotoDAL::SimplePhotoUpload($_FILES['photoname'], self::AVATAR_TEMP_DIR . DIRECTORY_SEPARATOR , $photoWidth, $photoHeight, 100);



					$destName = md5('photo' . microtime());
					if(file_exists(PATH_STATIC_CONTENT.'upload/File/'.$destName.'.jpg'))
					unlink(PATH_STATIC_CONTENT.'upload/File/'.$destName.'.jpg');


					$propW = $photoWidth/self::IMAGE_NORMAL_WIDTH;
					$propH = $photoHeight/self::IMAGE_NORMAL_HEIGHT;

					if ($propW > $propH) {
						$prop = $propH;
					} else {
						$prop = $propW;
					}

					//$photo = PhotoDAL::SaveTempFile($photoFile, $destName, '/upload/Structure', 0, 0, self::IMAGE_NORMAL_WIDTH*$prop, self::IMAGE_NORMAL_HEIGHT*$prop, self::IMAGE_NORMAL_WIDTH, self::IMAGE_NORMAL_HEIGHT);
					//maks szerokość
					//$photo = PhotoDAL::SaveTempFile($photoFile, $destName, '/upload/File', 0, 0, $photoWidth, $photoHeight, self::IMAGE_NORMAL_WIDTH,  $photoWidth/$prop);
					// maks wysokość
					//$photo = PhotoDAL::SaveTempFile($photoFile, $destName, '/upload/File', 0, 0, $photoWidth, $photoHeight, $photoHeight/$prop, self::IMAGE_NORMAL_HEIGHT);
					$photo = PhotoDAL::SaveTempFile($photoFile, $destName, '/upload/File', 0, 0, self::IMAGE_NORMAL_WIDTH*$prop, self::IMAGE_NORMAL_HEIGHT*$prop, self::IMAGE_NORMAL_WIDTH, self::IMAGE_NORMAL_HEIGHT);


					$objPhoto = new Picture();
					$objPhoto->SetLink($photo);
					$objPhoto->SetWeight(1);
					$objPhoto->SetPublication(1);
					$idPhoto = PictureDAL::Insert($objPhoto);
					$objFile->SetIdPicture($idPhoto);
					$destName = md5('photo' . microtime());


					$propW = $photoWidth/self::IMAGE_MINI_WIDTH;
					$propH = $photoHeight/self::IMAGE_MINI_HEIGHT;

					if ($propW > $propH) {
						$prop = $propH;
					} else {
						$prop = $propW;
					}
					$photoMini = PhotoDAL::SaveTempFile($photoFile, $destName, '/upload/File', 0, 0, self::IMAGE_MINI_WIDTH*$prop, self::IMAGE_MINI_HEIGHT*$prop, self::IMAGE_MINI_WIDTH, self::IMAGE_MINI_HEIGHT);
					$objPhoto = new Picture();
					$objPhoto->SetLink($photoMini);
					$objPhoto->SetWeight(1);
					$objPhoto->SetPublication(1);
					$idPhoto = PictureDAL::Insert($objPhoto);
					$objFile->SetIdPictureMini($idPhoto);
				}
				
				if (isset($data['deletePhoto'])) {
					$objFile->SetIdPictureMini(0);
					$objFile->SetIdPicture(0);
				}
				//===============================================================================================================================================================

//Utils::ArrayDisplay($objFileDescription);
				$iid = MfFileDAL::Save($objFile);
				$objFileDescription->SetIdMfFile($iid);

				MfFileDescriptionDAL::Save($objFileDescription);

				$this->smarty->assign('iid', $iid);
				//$this->AddRedirect(Router::GenerateUrl('indexFile', array('File'=> 'Index')), 0);
				$this->AddRedirect(Router::GenerateUrl('editStructure', array('id' => $idStructure)), 0);

			}	else {
				//$this->content=$this->FormatAjaxOutput($out, $param);
				//Utils::ArrayDisplay($out);

				$objFile->SetFileDescriptionObj($objFileDescription);
				$this->smarty->assign('objFile',$objFile);
				$datePublished = explode(" ",$objFile->GetDatePublication());

				$this->smarty->assign("datePublished", $datePublished[0]);
				$this->smarty->assign("timePublished", $datePublished[1]);

				foreach ($out as $item) {
					$error[$item['field']] = $item['msg'];
				}
				$this->smarty->assign('error',$error);

			}
		}

		$this->smarty->assign('objFile', $objFile);
	}

	public function DeleteAction($param) {
		$idStructure = SessionProxy::GetValue('idStructure');
		$logger = LoggerManager::getLogger(__CLASS__);

		$idFile = $param['idFile'];
		if ($idFile) {
			try {
				$objFile = MfFileDAL::GetById($idFile);

				if (file_exists($objFile->GetNamePath())) {
					unlink($objFile->GetNamePath());
				}

				MfFileDAL::Delete($objFile);

			} catch (Exception $e) {
				//Utils::ArrayDisplay($e);
				$logger->error('bład usunięcia pliku o id: '.$idFile);
			}

		}

		$this->AddRedirect(Router::GenerateUrl('editStructure', array('id' => $idStructure)), 0);
	}

	/**
	 * preDispatch
	 * @param array $param
	 * @return null
	 */
	public function preDispatch($param){
		$this->Run($param);
		$this->AddScript('dropDown.js');
		$this->AddScript('structure.js');
		$this->AddScript('Dosia.js');
		$this->AddScript('Link.js');
		$this->AddScript('drag-drop-folder-tree.js');
		//		//$this->AddScript('Validator.js');
		$this->AddScript('calendar.js');

		$this->RunShared('Auth', array());

		$this->RunShared('Structure', $param);
		$this->smarty->assign('idStucture', SessionProxy::GetValue('idStructure'));

		$this->smarty->assign('lang', 'pl');
		$this->smarty->assign('titleAdmin', 'Pliki');
		$this->smarty->assign('activeTab', 'index');

	}

	/**
	 * postDispatch
	 * @param array $param
	 * @return null
	 */
	public function postDispatch($param){

	}



}
