<?php

namespace App\Http\Controllers;

use App\Models\Artwork;
use App\Models\Podcast;
use App\Models\Episode;
use Illuminate\Http\Request;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rules\File;
use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Intervention\Image\Facades\Image;
use Illuminate\Support\Facades\Cache;
use ImageOptimizer;

class ArtworkController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $user = auth()->user();
        $artworks = Artwork::whereNotNull('approved_by')
            ->join('episodes', 'artworks.episode_id', '=', 'episodes.id')
            ->select('artworks.*', DB::raw('episodes.episode_number episode_number'))
            ->with('artist')
            ->with('podcast')
            ->with('episode')
            ->orderBy('episode_number', 'desc')
            ->orderBy('artworks.created_at', 'desc')
            ->paginate($perPage = 52, $columns = ['*'], $pageName = 'artworks');
        $podcasts = $this->publishedPodcasts();
        return view('explore.artworks', [
            'user' => $user,
            'pageTitle' => 'Explore',
            'artworks' => $artworks,
            'podcasts' => $podcasts,
        ]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create(Request $request)
    {
        $user = auth()->user();
        $podcasts = $this->publishedPodcasts();
        $request->session()->flash('success', '<h4>PLEASE READ!</h4>
            <p>When you submit your artwork, it will be stored for approval,
            this is because malicious users were using the site to dox and
            other vile behaviors. You will not see it in the list of artworks
            until it has been approved.</p>
            <h4>YOU DON\'T HAVE TO SUBMIT IT MULTIPLE TIMES!</h4>');
        return view('artworks.submit', [
            'user' => $user,
            'pageTitle' => 'Submit New Artwork',
            'podcasts' => $podcasts,
        ]);
    }

    public function pendingApproval(Request $request)
    {
        $user = auth()->user();
        if ($request->user()->cannot('approve', Artwork::class)) {
            abort(403);
        }
        $artworks = Artwork::whereNull('approved_by')
            ->orderBy('created_at', 'desc')
            ->paginate(50);
        $podcasts = $this->publishedPodcasts();
        return view('artworks.approvals', [
            'user' => $user,
            'pageTitle' => 'Approve Artworks',
            'podcasts' => $podcasts,
            'artworks' => $artworks,
        ]);
    }

    public function approve(Request $request)
    {
        $user = $request->user();
        if ($request->user()->cannot('approve', Artwork::class)) {
            abort(403);
        }
        $validated = $request->validate([
            'artwork_id' => 'required|exists:artworks,id'
        ]);
        $artwork = Artwork::find($request->artwork_id);
        if ($artwork->artist_id == $user->artists->first()->id) {
            return redirect('/approve-artwork');
        }
        if (is_null($artwork->approved_by)) {
            $artwork->approved_by = $user->artists->first()->id;
            $artwork->save();
        }
        return redirect('/approve-artworks');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request): RedirectResponse
    {
        $validator = Validator::make($request->all(), [
            'title' => ['required', 'max:255',],
            'podcast' => ['required', 'exists:podcasts,id',],
            'description' => ['nullable',],
            'file' => ['required', 'image', Rule::dimensions()->ratio(1)->minWidth(512),],
        ]);
        if ($validator->fails()) {
            return back()
                ->withErrors($validator)
                ->withInput();
        }
        Log::channel('artwork_import')->info('making new artwork model.');
        $podcast = Podcast::where('id', $request->podcast)->with(['episodes' => function($query) {
            $query->orderBy('episode_number', 'desc')->limit(1);
        }])->first();
        $episode = $podcast->episodes->first();
        $artist = auth()->user()->artists()->first();
        $rawFile = $request->file('file');
        $yearDirectory = now()->format('Y');
        $monthDirectory = now()->format('m');
        $indexPath = $yearDirectory . '/' . $monthDirectory . '/index.htm';
        $imgDirExists = Storage::disk('static')->exists('artworks/' . $indexPath);
        $thumbDirExists = Storage::disk('static')->exists('thumbnails/' . $indexPath);
        if (!$imgDirExists) {
            Storage::disk('static')->put('artworks/' . $indexPath, '');
        }
        if (!$thumbDirExists) {
            Storage::disk('static')->put('thumbnails/' . $indexPath, '');
        }
        $filename = $yearDirectory
            . '/'
            . $monthDirectory
            . '/'
            . Str::slug($artist->name)
            . '-'
            . Str::slug($request->title)
            . '_'
            . Str::random(8)
            . '.jpg';
        $artwork = Artwork::factory()->state([
            'title'       => $request->title,
            'artist_id'   => $artist->id,
            'description' => $request->description,
            'overlay_id'  => null,
            'podcast_id'  => $podcast->id,
            'episode_id'  => $episode->id,
            'filename'    => $filename,
            'created_at'  => now(),
            'updated_at'  => now(),
        ])->create();
        $img = Image::make($rawFile)->resize(3000, null, function($constraint) {
                $constraint->aspectRatio();
            })
            ->encode('jpg', 100)
            ->save(Storage::disk('static')->path('/artworks') . '/' . $artwork->filename);
        $thumbImg = Image::make($request->file('file'))->resize(512, null, function($constraint) {
                $constraint->aspectRatio();
            })
            ->encode('jpg', 100)
            ->save(Storage::disk('static')->path('/thumbnails') . '/' . $artwork->filename);
        ImageOptimizer::optimize(Storage::disk('static')->path('/artworks/' . $artwork->filename));
        ImageOptimizer::optimize(Storage::disk('static')->path('/thumbnails/' . $artwork->filename));
        $request->session()->flash('success', '<h4>Your artwork has been submitted successfully</h4><p>Someone with permission will approve it for public consumption shortly, <strong>you do not need to submit it again.</strong> - TYFYC and ITM!</p>');
        return redirect('/artworks');
    }

    /**
     * Display the specified resource.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  the id of the \App\Models\Artwork $id
     * @return \Illuminate\Http\Response
     */
    public function show(Request $request, $id)
    {
        $user = auth()->user();
        $artwork = Artwork::with(['podcast', 'episode', 'artist'])->find($id);

        if (!$artwork) {
            abort(404);
        }

        if (is_null($artwork->approved_by) && $user && $user->id != $artwork->id) {
            return redirect('artworks');
        }
        if (is_null($artwork->approved_by) && !$user) {
            return redirect('artworks');
        }
        return view('artworks.artwork', [
            'artwork' => $artwork,
            'user' => $user,
        ]);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\Artwork  $artwork
     * @return \Illuminate\Http\Response
     */
    public function edit(Artwork $artwork)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Artwork  $artwork
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Artwork $artwork)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Artwork  $artwork
     * @return \Illuminate\Http\Response
     */
    public function destroy(Artwork $artwork)
    {
        //
    }

    public function legacyArtLink(Request $request, $any = null)
    {
        phpinfo();
        dd($request->path());
        //$artwork = Artwork::where('legacy_filename', '/assets/artwork/')
    }

    public function downloadArchiveList(Request $request, $type = 'sd')
    {
        $artworks = Artwork::whereNotNull('approved_by')
            ->orderBy('created_at', 'desc')
            ->pluck('filename');
        $output = '';
        if ($type == 'sd') {
            foreach($artworks as $artwork) {
                $output .= '"https://static.noagendaartgenerator.com/thumbnails/' . $artwork . '"' . "\r\n";
            }
        } else {
            foreach($artworks as $artwork) {
                $output .= '"https://static.noagendaartgenerator.com/artworks/' . $artwork . '"' . "\r\n";
            }
        }
        return response($output, 200)
            ->header('Content-type', 'text/plain')
            ->header('Content-Length', strlen($output))
            ->header('Content-Disposition', 'attachment; filename="naartgen-archivelist-' . $type . '.txt"');
    }

    private function publishedPodcasts() {
        $podcasts = Cache::remember('publishedPodcasts', 30, function() {
            return Podcast::where('published', true)->get();
        });
        return $podcasts;
    }

}
