<?php
ApplicationSettings::RegisterDefaultSetting("blog", "posts_per_page", 10);

class Blog extends Controller {
	public function Index($page=1, IBlogPostRepository $repo=null){
		$count=(int)ApplicationSettings::GetSetting("blog", "posts_per_page");
		$offset=($page-1)*$count;
		$total=$repo->GetCount();
		$maxPages=$total/$count;
		
		$posts=$repo->GetLatest($count,$offset);
		
		$vars=array(
			"posts"=>$posts,
			"page"=>$page,
			"maxPages"=>$maxPages
		);
		return new View("Blog/index.view",$vars);
	}
	
	public function Page($page=1, IBlogPostRepository $repo=null) {
		return $this->Index($page,$repo);
	}
	
	public function Create($title,$draft){
		Breadcrumbs::Add("Create", "/blog/create");
		$post=new BlogPost();
		if (isset($title))
			$post->PostTitle=$title;
		if (isset($draft))
			$post->PostDraft=$draft;
		if ($post->PostTitle!="" && $post->PostDraft!=""){
			$post->Save();
			header("location:/blog/manage");
			return;
		}
		return new View("Blog/create.view",array("post"=>$post));
	}
	
	public function Manage(IBlogPostRepository $repo,$formSubmitted=false,$publish=null,$delete=null){
		Breadcrumbs::Add("Manage", "/blog/manage");
		if ($formSubmitted!=false && $formSubmitted==="yes"){
			if ($delete!=null){
				$post=new BlogPost($delete);
				$post->Delete();
			}
			if ($publish!=null){
				$post=new BlogPost($publish);
				$post->Publish();
			}
			header("location:/blog/manage");
			return;
		}
		
		$posts=$repo->GetAll();
		return new View("Blog/manage.view",array("posts"=>$posts));
	}
	
	public function Edit($postId,$title,$draft) {
		$post=new BlogPost($postId);
		Breadcrumbs::Add("Edit", "");
		if($title!=null && $draft!=null){
			$post->PostTitle=$title;
			$post->PostDraft=$draft;
			$post->Save();
		}
		return new View("Blog/create.view",array("post"=>$post));
	}
	
	public function View($url){
		if ($url==null){
			header("location:/blog");
			return;
		}
		$post=new BlogPost($url);
		if (!$post->PostId)
			return new View("E404/index.view");
		Breadcrumbs::Add(htmlspecialchars($post->PostTitle), "");
		return new View("Blog/view.view",array("content"=>$post->PostContent,"timestamp"=>$post->PostTimestamp));
	}
	
	public function ViewDraft($url){
		if ($url==null){
			header("location:/blog/manage");
			return;
		}
		$post=new BlogPost($url);
		if (!$post->PostId)
			return new View("E404/index.view");
		Breadcrumbs::Add("Draft", "");
		Breadcrumbs::Add(htmlspecialchars($post->PostTitle), "");
		return new View("Blog/view.view",array("content"=>$post->PostDraft,"timestamp"=>$post->PostTimestamp));
	}
}
