<?php

namespace app\controllers;

use app\models\contentList;
use app\models\User;
use app\models\Anime;
use app\models\Entry;
use \lithium\security\Auth;
use \lithium\util\Validator;


class AnimeListController extends \lithium\action\Controller {
	public $publicActions = array('view');

	public function view($username, $sort = "all")
	{
		$user = User::find('first', array('conditions' => compact('username')));

		$watching = array();
		$paused = array();
		$dropped = array();
		$planning = array();
		$finished = array();
		
		//The anime list comes back as a DocumentArray, so we can
		//parse through them with a foreach
		//For each entry,
		foreach($user->animelist as $entry)
		{
			//Sort it based on status
			switch($entry->my_status)
			{
				case "Completed": $finished[] = $entry; break;
				case "Watching": $watching[] = $entry; break;
				case "On-Hold" : $paused[] = $entry; break;
				case "Dropped" : $dropped[] = $entry; break;
				case "Plan to Watch": $planning[] = $entry; break;
			}
		}

		
		//In the future we can use set or something
		switch($sort)
		{
			case "planning" : return compact('user', 'planning'); break;
			case "completed" : return compact('user', 'finished'); break;
			case "onhold": return compact('user', 'paused'); break;
			case "watching" : return compact('user', 'watching'); break;
			case "dropped": return compact('user', 'dropped');
			default: return compact('user', 'watching', 'paused', 'dropped', 'planning', 'finished'); break;
		}
	}

	public function addsearch()
	{
		if (isset($this->request->query['Search'])) {
			$searchParam = '/' . $this->request->query['Search'] . '/i';
			if($this->request->query['Search'])
			{
				return Anime::search($searchParam);
			}
		}
	}

	//Ensure the correct user here 
	public function add($id = null)
	{
		//If id is null,
		if ('id' == null) {
			//Redirect them to the search page
			return $this->redirect('Animelist::addsearch');
		}

		//Find the requested anime
		$anime = Anime::find('first', array('conditions' => array('special_id' => $id)));
		$entry = null;


		//If data was submitted
		if ($this->request->data)
		{
			//Create an entry with the data
			$entry = Entry::create($this->request->data);
		

			//Get the current user
			$user = Auth::check('default');
			$username = $user['username'];

			//Break the tags into an array
			if (isset($this->request->data['tags']))
			{
				$entry->my_tags = explode(',', $this->request->data['tags']);
				unset($this->request->data['tags']);
			}

			if($entry->add($username))
			{

				//Redirect the user to their anime list
				return $this->redirect("/animelist/view/$username");	
			}
		}

		return compact('entry', 'anime'); 
	}

	public function edit($id = null)
	{
		if (id != null)
		{
			//Get the ani
		}
		else 
		{
			//Error message
		}
	}


}