<?php

namespace App\Http\Controllers\Gallery;

use App\Album;
use App\AlbumRedirect;
use App\Facade\Theme;
use App\Facade\UserConfig;
use App\Helpers\ConfigHelper;
use App\Helpers\DbHelper;
use App\Http\Controllers\Controller;
use App\Http\Requests;
use App\VisitorHit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\DB;

class AlbumController extends Controller
{
    public function index(Request $request, $albumUrlAlias)
    {
        $album = DbHelper::getAlbumByPath($albumUrlAlias);
        if (is_null($album))
        {
            // Check redirects (remove the first 'a' at the beginning - e.g. "a/Florida-2015" => "/Florida-2015"
            $requestPath = preg_replace('/^a/', '', $request->path());
            $redirect = AlbumRedirect::where('source_url', $requestPath)->first();

            if (is_null($redirect))
            {
                // No redirect found either - bail out
                App::abort(404);
                return null;
            }

            $album = DbHelper::getAlbumById($redirect->album_id);
            return redirect($album->url());
        }

        $this->authorizeForUser($this->getUser(), 'view', $album);

        $validViews = UserConfig::allowedAlbumViews();
        $requestedView = strtolower($request->get('view'));
        if (!in_array($requestedView, $validViews))
        {
            $requestedView = strtolower($album->default_view);

            if (!in_array($requestedView, $validViews))
            {
                $requestedView = $validViews[0];
            }
        }

        // Record the visit to the album
        if (UserConfig::get('enable_visitor_hits'))
        {
            DB::transaction(function () use ($album, $request, $requestedView)
            {
                $album->hits++;
                $album->save();

                VisitorHit::fromRequest($request, $album->id, null, $requestedView);
            });
        }

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

        // Load child albums and their available children
        $childAlbums = DbHelper::getChildAlbums($album);
        foreach ($childAlbums as $childAlbum)
        {
            $childAlbum->children_count = DbHelper::getChildAlbumsCount($childAlbum);
        }

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