<?php

namespace App\Http\Controllers;


use App\Models\Gallery;
use App\Models\Image;
use App\Models\Tenant;

use Illuminate\Http\Request;

use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Support\Facades\Auth;


class PublicController extends BaseController
{

    public static $size = ["pixel" => 100, "small" => 300, "medium" => 600, "big" => 1200];

    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    public function listGalleriesViewAPI($name, Request $request) {
        $data = [];
        $tenant = Tenant::query()->where("url", "=", $name)->firstOrFail();
        $galleries = Gallery::query()
            ->where("tenant", "=", $tenant->id)
            ->where("status", "=", "online")
            ->where("listed", "=", 1)
            ->orderByDesc("gallery_create_time")
            ->orderByDesc("created_at")
            ->get();
        $parser = new \Parsedown();
        foreach ($galleries as $gallery) {
            $gallery->html = $parser->parse($gallery->description);
        }

        $g = collect($galleries);
        $page = $request->input("page", 1);
        $r = $g->forPage($page, 10);

        $next = null;
        $preview = null;

        if($page > 1) {
            $preview = url("/".$tenant->url.".json?page=".($page-1));
        }

        if(($g->count() / 10) > $page) {
            $next = url("/".$tenant->url.".json?page=".($page+1));
        }

        return response()->json(["pagination" => [
                "total" => $g->count(),
                "items_per_page" => 10,
                "pages" => ($g->count() / 10),
                "preview" => $preview,
                "next" => $next],
            "data" => [
                "galleries" => \App\Http\Resources\Gallery::collection($r)
            ]]);
    }
    public function listGalleriesView($name, Request $request) {
        $tenant = Tenant::query()->where("url", "=", $name)->firstOrFail();
        $galleries = Gallery::query()
            ->where("tenant", "=", $tenant->id)
            ->where("status", "=", "online")
            ->where("listed", "=", 1)
            ->orderByDesc("gallery_create_time")
            ->orderByDesc("created_at")
            ->get();
        $parser = new \Parsedown();
        foreach ($galleries as $gallery) {
            $gallery->html = $parser->parse($gallery->description);
        }

        $theme = $tenant->template;
        if($request->input("theme", false) && $tenant->owner == Auth::id()) {
            $theme = $request->input("theme");
        }
        return view("themes.tenant.".$theme.".list", ["galleries" => $galleries, "tenant" => $tenant]);
    }

    public function listGalleryImagesViewAPI($tenant, $gallery, Request $request) {
        $tenant = Tenant::query()->where("url", "=", $tenant)->firstOrFail();
        $gallery = Gallery::getByTenantAndUrl($tenant->id, $gallery);
        if($gallery->status == "online" || (Auth::check() && $gallery->status == "preview" && Auth::user()->id == $tenant->owner)) {
            $images = Image::query()
                ->where("gallery", "=", $gallery->id)
                ->whereNull("deleted_at")
                ->orderBy("rating")
                ->orderBy("DateTimeOriginal")
                ->get();
        } else {
            abort( 404);
        }

        $parser = new \Parsedown();
        $gallery->html = $parser->parse($gallery->description);

        return response()->json(["data" => ["gallery" => new \App\Http\Resources\Gallery($gallery), "images" => \App\Http\Resources\Image::collection(collect(($images)))]]);

        return view("themes.gallery.".$theme.".list", ["gallery" => $gallery, "tenant" => $tenant, "images" => $images]);
    }

    public function listGalleryImagesView($tenant, $gallery, Request $request) {
        $tenant = Tenant::query()->where("url", "=", $tenant)->firstOrFail();
        $gallery = Gallery::getByTenantAndUrl($tenant->id, $gallery);
        if($gallery->status == "online" || (Auth::check() && $gallery->status == "preview" && Auth::user()->id == $tenant->owner)) {
            $images = Image::query()
                ->where("gallery", "=", $gallery->id)
                ->whereNull("deleted_at")
                ->orderBy("rating")
                ->orderBy("DateTimeOriginal")
                ->get();
        } else {
            abort( 404);
        }

        $parser = new \Parsedown();
        $gallery->html = $parser->parse($gallery->description);

        $theme = $tenant->gallery_default_theme;
        if($request->input("theme", false) && $tenant->owner == Auth::id()) {
            $theme = $request->input("theme");
        }

        return view("themes.gallery.".$theme.".list", ["gallery" => $gallery, "tenant" => $tenant, "images" => $images]);
    }

    public function returnWatermakeFile(\App\Helper\Image $imageHelper, \App\Helper\Access $accessHelper) {
        $tenant = Tenant::query()->where("id", "=", session("current_tenant_id"))->firstOrFail();
        $imageModel = Image::query()->where("id", "=", $tenant->watermark)->firstOrFail();
        $img = $imageHelper->getRawImage($imageModel);
        $accessHelper->add($imageModel, $img, \App\Helper\Access::TYPE_CACHE);
        return $img->response();
    }

    public function returnImageFile($tenant_url, $gallery_url, $image_id, \App\Helper\Image $image, \App\Helper\Access $access, Request $request) {
        $sizeName = $request->input("size", "medium");
        if(!array_key_exists($sizeName, self::$size)) {
            abort(400, "Size not exists");
        }
        $size = (int)self::$size[$sizeName];

        $imageModel = Image::query()->where("id", "=", $image_id)->firstOrFail();
        if(!$image->validateGalleryAndTenant($imageModel, $gallery_url, $tenant_url)) {
            abort(404);
        }
        $img = $image->getImage($imageModel, $size);
        $typ = \App\Helper\Access::TYPE_S3;
        if($img->getDrive() == "cache") {
            $typ = \App\Helper\Access::TYPE_CACHE;
        }
        $access->addById($image_id, $img, $typ);
        return $img->response();
    }
}
