<?php defined('SYSPATH') OR die('No direct access allowed.');

class gen {

	/**
	 * 
	 *
	 * @param   string   image
	 * @return  string
	 */
	public static function lang($text)
	{
		if(strpos($text," "))
			return $text;
		$value = i18n::get($text);
		if($value == $text)
			$value =  utf8::ucwords(inflector::humanize($text));
		return $value;
	}
	public static function arr_get($array, $key, $default="")
	{
		if($array){
			return Arr::get($array, $key);
		}
		return $default;
	}
	
	public static function re_back()
	{
		$address = "";
		if(Request::$referrer != Request::instance()->uri)
		{
			$address = Request::$referrer;
		}
		$address .= Url::query();
		Request::instance()->redirect($address);
	}
	
	private function display_tree($node,$dataset) {
		$task = $node['orm'];
		$ret = '<div class="task-item" id="'.$task->id.'">'.template::aimg("#".$task->id,"done".$task->status.".gif", null,array("class" => "check","id"=>$task->id))
		." ".html::anchor("#",$task->title,array("class" =>"done".$task->status)).'</div>'.
		'<div class="tooltip">
			<span>'
			.html::anchor("todo/edit/".$task->id,"Edit")
			.html::anchor("todo/delete/".$task->id,"Delete")
			.'</span><h2>'. $task->title.'</h2>'.
			 $task->description.
		'</div>';
		if(!empty($node["children"]))
		{
			$ret .="<ul>";
			foreach ($node["children"] as $child) {
				$ret .= "<li>";
				$ret .= $this->display_tree($child,$dataset);
				$ret .= "</li>";
			}
			$ret .="</ul>";
		}
		return $ret;
	}
	
	public static function build_tree($orm_list) {
		
		$tree = array();
		$dataset = array();
		
		foreach($orm_list as $orm)
		{
			$dataset[$orm->id]["orm"] = $orm;

			if(!isset($dataset[$orm->id]["children"]))
			{
				$dataset[$orm->id]["children"] = array();
			}
			if($orm->parent_id === NULL)
			{
				$tree[] = &$dataset[$orm->id];
			}
			else
			{
				$pid = $orm->parent_id;
				if(isset($dataset[$pid]))
				{
					$dataset[$pid]['children']= array_merge($dataset[$pid]['children'], array(&$dataset[$orm->id]));
					/*echo $dataset[$pid]["orm"]." cocuklar<br>";
					foreach($dataset[$pid]['children'] as $child)
					{
						echo " " . $child["orm"]->title;
					}*/
				}
				else
				{
					$dataset[$pid]["children"] =array(&$dataset[$orm->id]);
				}
			}
		}
		$return = "<ul>";
		$gen = new gen();
		foreach ($tree as $node)
		{
			$return .= "<li>";
			$return .= $gen->display_tree($node,$dataset);
			$return .= "</li>";
		}
		$return .= "</ul>";
		
		return $return; 
	}
	public static function do_post_request($url)
	{
		$optional_headers = null;
		$data = http_build_query($_POST);
		
		$params = array('http' => array(
					 'method' => 'POST',
					 'content' => $data
				  ));
		if ($optional_headers !== null) {
		   $params['http']['header'] = $optional_headers;
		}
		$ctx = stream_context_create($params);
		$fp = @fopen($url, 'rb', false, $ctx);
		if (!$fp) {
		   throw new Exception("Problem with $url");
		}
		$response = @stream_get_contents($fp);
		if ($response === false) {
		   throw new Exception("Problem reading data from $url");
		}
		return $response;
	}
	
	public static function to_slug($string)
	{
		$string = utf8::transliterate_to_ascii(utf8::strtolower($string));
		return url::title(str_replace("ı","i",$string));
	}
	public static function now()
	{
		return date("Y-m-d H:i:s");
	}
	public static function paged(&$orm, $view, $data = NULL)
	{
		$page_list = new View($view, $data);
		
		$page_num = gen::arr_get($_GET, 'page', 1);
		$per_page = Kohana::config("site.per_page");
		$offset   = ($page_num - 1) * $per_page;
		$pages = $orm->limit($per_page)->offset($offset)->find_all(); 
		$pagination = Pagination::factory(array
		(
			
			'style' => 'digg',
			'items_per_page' => $per_page,
			'query_string' => 'page',
			'total_items' => $orm->count_all(),
		));
		
		if($pagination->total_pages > 1)
			$page_list->pagination = $pagination;
		else
			$page_list->pagination ="";
		$items_name = inflector::plural(strtolower(substr(get_class($orm), 6)));
		$page_list->$items_name = $pages;
		
		//echo "dikkat: ". Kohana::debug($page_list);
		
		
		
		return $page_list;
	}
}