<?php

namespace App\Http\Controllers\Movie;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use App\Http\Controllers\Controller;
use App\Http\Traits\PagingTrait;

class TrailerController extends Controller
{
    use PagingTrait;

    public function __construct() {
        $this->middleware('front');
    }

    /**
     * 영화 예고편
     * @method GET
     * @see /movie/trailer
     */
    public function index(Request $request)
    {
        $page = $request->get('page', 1);
        $keyword = $request->get('keyword');
        $sort = $request->get('sort', 1); // 개봉순, 인기순, 평점 높은순
        $params = [
            'api_key' => TMDB_API_KEY,
            'language' => 'ko',
            'page' => $page,
            'region' => 'kr'
        ];

        if(!$keyword) {
            $url = (TMDB_HOST . match(intval($sort)) {
                1 => TMDB_GET_UPCOMING,
                2 => TMDB_GET_POPULAR,
                3 => TMDB_GET_TOP_RATED,
            });
        }else{
            $url = (TMDB_HOST . TMDB_GET_SEARCH_MOVIE);
            $params['region'] = null;
            $params['query'] = $keyword;
        }

        $cacheName = ($url . join($params));
        if (!$data = Cache::get($cacheName))
        {
            // 곧 개봉 예정
            $response = Http::get($url, $params);

            $total = 0;
            $list = [];
            $paginator = null;
            if($response->ok()) {
                $trailers = json_decode($response->body());
                foreach($trailers->results as $row) {
                    $row->posterURL = ('https://image.tmdb.org/t/p/original' . $row->poster_path);

                    // 예고편 조회
                    $res = Http::get(sprintf(TMDB_HOST . TMDB_GET_VIDEOS, $row->id), [
                        'api_key' => TMDB_API_KEY,
                        'language' => 'ko'
                    ]);

                    $row->thumbURL = "";
                    if($res->ok()) {
                        $row->videoMeta = current((json_decode($res->body()))->results);
                        if($row->videoMeta) {
                            $row->thumbURL = sprintf('https://img.youtube.com/vi/%s/0.jpg', $row->videoMeta->key);
                        }
                    }

                    $list[] = $row;
                    $total++;
                }
                $paginator = $this->getPaginator($trailers->results, $trailers->total_results, 20, $trailers->page);
            }

            $data = (object)[
                'total' => $total,
                'list' => $list,
                'paginator' => $paginator
            ];

            Cache::put($cacheName, $data, CACHE_EXPIRE_TIME);
        }

        return view('movie.trailer.index', [
            'page' => $page,
            'keyword' => $keyword,
            'sort' => $sort,
            'total' => $data->total,
            'list' => $data->list,
            'paginator' => $data->paginator
        ]);
    }
}
