<?php
/**
 * Klasa do obsługi plików
 *
 */
class MfFileDAL extends DefaultDAL {

	protected static $objClassName;
	protected static $objClassTable;
	protected static $objClassTablePK;
	private static $optClass;

	public static function Save( $obj) {
		$id = null;
		if($obj->GetId()==-1) {
			$id = self::Insert($obj);
		} else {
			self::Update($obj);
			$id = $obj->GetId();
		}

		return $id;
	}


	/**
     * @param Feed $obj
     *
     */
	public static function Insert($obj) {

		$dalData = new DalData();
		$dalData->setObjClassTable(self::GetObjClassTable());
		$dalData->setObj($obj);
		$id = self::DefaultInsert($dalData);

		return $id;
	}
	/**
     * @param Text $obj
     *
     */
	public static function Update($obj) {
		//Utils::ArrayDisplay($obj);
		$dalData = new DalData();
		$dalData->setObjClassTable(self::GetObjClassTable());
		$dalData->setObjClassTablePK(self::GetObjClassTablePK());
		$dalData->setObj($obj);
		return self::DefaultUpdate($dalData);
	}

	/**
     *
     * @param integer $id
     *
     */
	public static function Delete($obj) {
		$dalData = new DalData();
		$dalData->setObjClassTable(self::GetObjClassTable());
		$dalData->setObjClassTablePK(self::GetObjClassTablePK());
		$dalData->setObj($obj);
		
		MfFileDescriptionDAL::DeleteByParentId($obj->GetId());
		
		return self::DefaultDelete($dalData);
	}

	/**
     *
     * @param  $id
     * @return MfFile $obj
     */
	public static function GetById($id, $lang = 'pl') {
		$dalData = self::GetDalDataObj();
		$dalData->setCondition(array('mf_file.'.self::GetObjClassTablePK()=>$id, 'lang' => $lang));
		$dalData->setJoin(array('MfFileDescription' => ' LEFT JOIN mf_file_description ON mf_file.id_mf_file=mf_file_description.id_mf_file'));
		$dalData->setLimit(1);
		$result = self::GetResult($dalData);
		if ((count($result) > 0) && (is_object($result[0]))) {
			return $result[0];
		} else {
			throw new Exception('Brak rekordu w tablicy '.self::GetObjClassTable().' o id <b>'.$id.'</b>!');
		}
	}
	
	public static function GetResult($dalData) {
		$dalData->setJoin(array('MfFileDescription' => ' LEFT JOIN mf_file_description ON mf_file.id_mf_file=mf_file_description.id_mf_file'));
		return self::DefaultGetResult($dalData);
	}

	
	public static function GetEmptyObj() {
		//Utils::ArrayDisplay('tu jestem ');
		$obj = new MfFile(-1);
		$obj->SetFileDescriptionObj(MfFileDescriptionDAL::GetEmptyObj());
		return $obj;
	}

	public static function GetArrayObjAll() {

	}

	public static function GetResultOld($data, $queryFields = array(), $limit = 0, $sortBy = null, $count = null) {

		if(!is_array($data)){
			$data = array();
		}

		$db = Registry::Get('db');

		$queryCacheName = __CLASS__ . "_" . __FUNCTION__ . "_" . md5(implode($queryFields));

		if(isset(QueryCacheTemp::$cacheQuery[$queryCacheName])) {
			$sql = QueryCacheTemp::$cacheQuery[$queryCacheName];
		} else {
			if($count == true) {
				$select = "count(`mf_file`.`id_mf_file`) as count";
			} else {
				$select =" " . SQL::ToSelect(self::GetOptClass(),$queryFields) . " ";
			}

			$sql = " SELECT $select FROM " . self::GetObjClassTable() . ", mf_file_description WHERE 1=1 AND mf_file.id_mf_file=mf_file_description.id_mf_file ";
			$q = new QueryCache($queryCacheName,$sql);
		}

		foreach ($data as $key => $value) {
			if($key == "id") {
				$key = 'id_mf_file';
			}

			if(is_array($value)) {
				$sql .= ( is_numeric($value['value']) || $value ? " AND ".$key." ".$value['condition']." ". $value['value'] : "");
			} else {
				$sql .= ( is_numeric($value) || $value ? " AND ".$key." = '". $value ."'": "");
			}
		}

		$sql .= ( $sortBy ? " ORDER BY $sortBy " : "").
		( $limit ? " LIMIT " . $limit : "").
		" ";

		$stmt = $db->prepare($sql)
		->execute();

		//Utils::ArrayDisplay($sql);
		
		$array = $stmt->fetchAllAssoc();

		if($count == true) {
			return $array[0]['count'];
		}

		$done = array();

		for($i=0;$i<count($array);$i++) {
			$className=self::GetObjClassName();
			$obj = new $className();
			$obj->FromArray($array[$i],1);
			$done[] = $obj;
		}

		return $done;

	}

	public static function GetList($data = array(), $limit = 20, $sortBy = 'id_mf_file') {
		$dalData = self::GetDalDataObj();		
		$dalData->setJoin(array('MfFileDescription' => ' LEFT JOIN mf_file_description ON mf_file.id_mf_file=mf_file_description.id_mf_file'));
		$dalData->setCondition($data);
		$dalData->setLimit($limit);
		$dalData->setSortBy($sortBy);
		$result = self::GetResult($dalData);		
		return $result;

	}

	public static function GetByLink($sourceType, $sourceId, $lang) {

		$data = array('mf_link.source_type'=>'"'.$sourceType.'"', 'mf_link.id_source'=>$sourceId, 'mf_link.destination_type'=>'"'.self::GetObjClassTable().'"', 'mf_link.id_destination'=>self::GetObjClassTable().".".self::GetObjClassTablePK(), 'mf_link.id_mf_link'=>'mf_link_description.id_mf_link', 'mf_link_description.lang'=>'"'.$lang.'"');
		$sortBy = 'mf_link.link_type, mf_link.link_type';
		$queryFields = array();
		$limit = null;
		$count = null;

		$db = Registry::Get('db');

		$queryCacheName = __CLASS__. "_" .__FUNCTION__. "_" .md5(implode($queryFields));

		if(isset(QueryCacheTemp::$cacheQuery[$queryCacheName])) {
			$sql = QueryCacheTemp::$cacheQuery[$queryCacheName];
		} else {
			if($count == true) {
				$select = "count(*) as count";
			} else {
				$select =" " . SQL::ToSelect(self::GetOptClass(),$queryFields) . " ";
			}

			$sql = " SELECT $select, mf_link_description.description as mf_link_description, mf_link.weight as mf_link_weight, mf_link.link_type as mf_link_type FROM " . self::GetObjClassTable() . ", mf_link, mf_link_description WHERE 1=1 ";
			$q = new QueryCache($queryCacheName,$sql);
		}

		foreach ($data as $key => $value)
		{
			if($key == "id")
			$key = $objId ;

			if(is_array($value))
			$sql .= ( is_numeric($value['value']) || $value ? " AND ".$key." ".$value['condition']." ". $value['value'] : "");
			else
			$sql .= ( is_numeric($value) || $value ? " AND ".$key." = ". $value : "");
		}

		$sql .= ( $sortBy ? " ORDER BY $sortBy " : "").
		( $limit ? " LIMIT " . $limit : "").
		" ";

		$stmt = $db->prepare($sql)
		->execute();


		$array = $stmt->fetchAllAssoc();

		if($count == true) {
			return  $array[0]['count'];
		}

		$done = array();

		for($i=0;$i<count($array);$i++)
		{
			$className=self::GetObjClassName();
			$obj = new $className();
			$obj->FromArray($array[$i],1);
			$obj->SetMfLinkDescription($array[$i]['mf_link_description']);
			$obj->SetMfLinkWeight($array[$i]['mf_link_weight']);
			$obj->SetMfLinkType($array[$i]['mf_link_type']);
			$obj->SetLang($lang);
			$done[] = $obj;
		}
		return $done;

	}

	public function SaveFromPost($_POST, $className) {
		//Utils::ArrayDisplay($_POST);
		if (isset($_POST['File']['idFile']) && $_POST['File']['idFile'] > 0) {
			
			$objFile = MfFileDAL::GetById($_POST['File']['idFile']);
			$objFileDescription = MfFileDescriptionDAL::GetResult(array('publication' => 1, 'lang' => $objFile->GetLang(), 'id_mf_file' => $objFile->GetId()), array('id_mf_file_description', 'title', 'description', 'shortnote'));
			$objFileDescription = $objFileDescription[0];
		} else {
			$objFile = new MfFile();
			$objFileDescription = new MfFileDescription();

		
		}

		//				var_dump($objFileDescription->GetId());

		$objFile->SetDate(date('Y-d-m'));
		$objFile->SetWeight(10);
		//$objFile->SetPublication(1);
		//Utils::ArrayDisplay($objFile);
		$iid = MfFileDAL::Save($objFile);

		$objFileDescription->SetLang('pl');
		$objFileDescription->SetDescription($_POST['File']['tresc']);
		$objFileDescription->SetShortnote($_POST['File']['zajawka']);
		$objFileDescription->SetTitle($_POST['tytul']);
		$objFileDescription->SetBrowserTitle($_POST['File']['tytulWPrzegladarce']);
		$objFileDescription->SetPublication($_POST['publication']);
		$objFileDescription->SetIdMfFile($iid);

		MfFileDescriptionDAL::Save($objFileDescription);
		
		return $iid;
	}
	
	public function Special($id = -1, $specjal) {
		$db = Registry::Get('db');



		$sql = "UPDATE mf_file SET special = $specjal
					WHERE id_mf_file = $id	";
		//Utils::ArrayDisplay($sql);
		$stmt = $db->prepare($sql)
		->execute();
	}

	/**
	 * Pusty konstruktor
	 *
	 */
	public function __construct() {

	}

	public static function GetObjClassName() {
		if(self::$objClassName != '') {
			$class = self::$objClassName;
		} else {
			$class = str_replace('DAL', '', __CLASS__);
		}

		return $class;
	}

	public static function GetOptClass() {
		if(self::$optClass!=null) {
			return self::$optClass;
		} else {
			return self::GetObjClassName();
		}
	}

	public static function GetObjClassTablePK() {
		if(self::$objClassTablePK != '') {
			$return = self::$objClassTablePK;
		} else {
			$class = self::GetObjClassName();
			$classObj = new $class();
			$return = $classObj->GetClassTablePK();
		}
		return $return;
	}

	public static function GetObjClassTable() {
		if(self::$objClassTable!='') {
			$return = self::$objClassTable;
		} else {
			$class = self::GetObjClassName();
			$classObj = new $class();
			$return = $classObj->GetTableName();
		}

		return $return;
	}
	
		/**
		 * Enter description here...
		 *
		 * @return  DalData $dalData
		 */
		public static function GetDalDataObj() {

		$dalData = new DalData();
		$dalData->setObjClassName(self::GetObjClassName());
		$dalData->setObjClassTable(self::GetObjClassTable());
		$dalData->setObjClassTablePK(self::GetObjClassTablePK());
		$dalData->setOptClass(self::GetOptClass());
		//$dalData->setDatabaseType('dbTemp');

		return $dalData;
	}
}
?>