<?php

namespace App\Http\Controllers\Gallery;

use App\Facade\Theme;
use App\Facade\UserConfig;
use App\Helpers\DbHelper;
use App\Http\Controllers\Controller;
use App\Label;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\DB;
use Symfony\Component\HttpFoundation\Request;

class LabelController extends Controller
{
    public function index(Request $request)
    {
        $labels = Label::orderBy('name')->get();

        /** @var Label $label */
        foreach ($labels as $label)
        {
            $label->photos_count = $label->photoCount();
        }

        return Theme::render('gallery.labels', ['labels' => $labels]);
    }

    public function show(Request $request, $labelAlias)
    {
        $label = Label::where('url_alias', $labelAlias)->first();
        if (is_null($label))
        {
            App::abort(404);
        }

        $validViews = UserConfig::allowedAlbumViews();
        $requestedView = strtolower($request->get('view'));
        if (!in_array($requestedView, $validViews))
        {
            $requestedView = $validViews[0];
        }

        $allowedAlbumIDs = DbHelper::getAlbumIDsForCurrentUser();

        if ($label->photos()->count() == 0)
        {
            $requestedView = 'empty';
            $photos = [];
        }
        else if ($requestedView != 'slideshow')
        {
            $photos = $label->photos()
                ->whereIn('album_id', $allowedAlbumIDs)
                ->orderBy(DB::raw('COALESCE(photos.taken_at, photos.created_at)'))
                ->paginate(UserConfig::get('items_per_page'));
        }
        else
        {
            // The slideshow view needs access to all photos, not paged
            $photos = $label->photos()
                ->whereIn('album_id', $allowedAlbumIDs)
                ->orderBy(DB::raw('COALESCE(photos.taken_at, photos.created_at)'))
                ->get();
        }

        if (count($photos) == 0)
        {
            $requestedView = 'empty';
        }

        return Theme::render(sprintf('gallery.label_%s', $requestedView), [
            'allowed_views' => $validViews,
            'current_view' => $requestedView,
            'label' => $label,
            'photos' => $photos
        ]);
    }
}