<?php

class SearchController extends \BaseController {

	/**
	 * Display a listing of the resource.
	 * GET /pages
	 *
	 * @return Response
	 */
	public function index($title)
	{
		$settings = Setting::first();
		$youtubeID = 0;
		$limit = $settings->per_page;
        $p = Input::get('page');
        $offset = isset($p) ? $p-1 : 0;
        $offset = $offset*$limit;
        $tracks = array();
        $title = str_replace('-', ' ', $title);
        if (isset($settings->soundcloud_key) && !empty($settings->soundcloud_key)) {
            try {
            //get tracks from soundcloud
                $jsonData = file_get_contents('https://api.soundcloud.com/tracks.json?offset='.$offset.'&limit='.$limit.'&client_id='.$settings->soundcloud_key.'&q='.urlencode($title));
            } catch (ErrorException $ex) {
                $jsonData = "[]";
            }
            if ($jsonData != "[]") {
                $jsonData = json_decode($jsonData, true);
                foreach ($jsonData as $track) {
                    $tracks[] = array('id' => $track['id'],
                                    'title' => htmlspecialchars($track['title']),
                                    'size' => $track['original_content_size'],
                                    'image' => isset($track['artwork_url']) ? $track['artwork_url'] : URL::asset('assets/images/artwork.jpg'),
                                    'duration' => $track['duration'],
                                    'username' => $track['user']['username'],
                                    'username-slug' => $track['user']['permalink']
                                );
                }
            }

            try {
                //get related video link from youtube
                $youtubeData = file_get_contents('https://www.googleapis.com/youtube/v3/search?part=id&type=video&key='.$settings->youtube_key.'&maxResults=1&q='.urlencode($title));
            } catch (ErrorException $ex) {
                $youtubeData = false;
            }
            if ($youtubeData) {
                $youtubeData = json_decode($youtubeData, true);
                $youtubeData = $youtubeData['items'];
                if (isset($youtubeData[0])) {
                    $youtubeID = $youtubeData[0]['id']['videoId'];
                }
            }
        }

        $max = 200;
        $current_count = count($tracks);
        if ($current_count < $settings->per_page) {
            $max = $offset*$settings->per_page + $current_count;
        }

        //create a custom paginator
        $pagination = Paginator::make($tracks, $max, $settings->per_page)->links('pagination::simple');
        
        //create a custom paginator
		return View::make('search.index', array('tracks' => $tracks, 'title' => $title, 'pagination' => $pagination, 'youtubeID' => $youtubeID));
	}

	/**
	 * Show the form for creating a new resource.
	 * GET /pages/create
	 *
	 * @return Response
	 */
	public function getTrack($title, $id)
	{
		$settings = Setting::first();
        $data = file_get_contents('https://api.soundcloud.com/tracks/'.trim($id).'?client_id='.$settings->soundcloud_key);
        $data = json_decode($data, true);

        $tracks = array();

		$tracks[] = array('id' => $data['id'],
                                    'title' => htmlspecialchars($data['title']),
                                    'size' => $data['original_content_size'],
                                    'image' => isset($data['artwork_url']) ? $data['artwork_url'] : URL::asset('assets/images/artwork.jpg'),
                                    'duration' => $data['duration'],
                                );
		return View::make('search.index', array('tracks' => $tracks, 'title' => $title, 'pagination' => null));
	}

	/**
	 * Store a newly created resource in storage.
	 * POST /pages
	 *
	 * @return Response
	 */
	public function store()
	{
		//
	}

	/**
	 * Display the specified resource.
	 * GET /pages/{id}
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function show($name)
    {
    	$category = Category::where('slug', $name)->first();
    	if($category)
    	{
        	$ptitle = 'All '. $category->name . ' Albums';
        	return View::make('album.list', array('data' => $category, 'ptitle' => $ptitle));
        }
    }

    public function showAdmin($slug)
    {
    	$category = Category::where('slug', $slug)->first();
    	if($category)
    	{
        	$ptitle = 'All '. $category->name . ' Albums';
        	return View::make('admin.album.search', array('data' => $category, 'ptitle' => $ptitle));
        }
    }

	/**
	 * Show the form for editing the specified resource.
	 * GET /pages/{id}/edit
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function edit($id)
	{
		//
	}

	/**
	 * Update the specified resource in storage.
	 * PUT /pages/{id}
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function update($id)
	{
		$input = Input::all();
        $validator = Validator::make(
            $input,
            array(
                'name' => 'required|between:2,100',
            )
        );

        if ($validator->passes()) {

        	$category = Category::where('id', $id)->first();
        	$category->name = $input['name'];
        	$category->slug = Custom::slugify($input['name']);
        	$category->save();

        	return json_encode(array('message' => 'successfull', 'status' => 'success'));

        } else {
            $message = $validator->messages()->all()[0];
            return json_encode(array('message' => $message, 'status' => 'error'));
        }
	}

	/**
	 * Remove the specified resource from storage.
	 * DELETE /pages/{id}
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function destroy($id)
	{
		//
	}

}