<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Intervention\Image\Facades\Image;
use Illuminate\Support\Facades\Storage;
use Carbon\Carbon;
use App\Models\User;
use App\Models\Artist;
use App\Models\Podcast;
use App\Models\Episode;
use App\Models\Artwork;
use ImageOptimizer;

class GetMissingArtworkMovedCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'naart:wrapup';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $missingArtworks = DB::connection('legacy')->select('SELECT * FROM artworks WHERE id > 30835 AND approved_by IS NOT NULL');
        foreach ($missingArtworks as $missingArtwork) {
            $localPath = '/legacypublic' . $missingArtwork->path . '/' . $missingArtwork->filename;
            $user = User::where('legacy_id', $missingArtwork->user_id)->with('artists')->first();
            $artwork = Artwork::where('legacy_id', $missingArtwork->id)->first();
            $episode = Episode::where('legacy_id', $missingArtwork->episode_id)->first();
            $approver = User::where('legacy_id', $missingArtwork->approved_by)->with('artists')->first();
            if ($artwork) {
                $this->line('Artwork ID: ' . $artwork->id);
            }
            if ($episode) {
                $this->line('Episode: ' . $episode->episode_number . ' "' . $episode->title . '"');
            }
            if (!$artwork) {
                $newFilename = $this->uniqueName($episode, $user, $missingArtwork);
                $state = [
                    'title' => $missingArtwork->title,
                    'description' => '',
                    'artist_id' => $user->artists->first()->id,
                    'episode_id' => $episode->id,
                    'podcast_id' => 1,
                    'overlay_id' => null,
                    'filename'  => $newFilename . '.jpg',
                    'created_at' => Carbon::parse($missingArtwork->created_at),
                    'updated_at' => Carbon::parse($missingArtwork->updated_at),
                    'legacy_id' => $missingArtwork->id,
                    'approved_by' => $approver->artists->first()->id,
                ];
                $artwork = Artwork::factory()->state($state)->create();
            }
            $this->line('Artist: ' . $user->artists->first()->name);
            $this->line($localPath);
            $filename = 'artworks/' . $artwork->filename;
            $thumbnailName = 'thumbnails/' . $artwork->filename;
            if (Storage::disk('static')->exists($filename)) {
                $this->error($filename  . ' already exists. ' . Storage::disk('static')->size($filename));
            }
            if (Storage::disk('static')->exists($thumbnailName)) {
                $this->error($thumbnailName . ' already exists. ' . Storage::disk('static')->size($thumbnailName));
            }
            $img = Image::make($localPath)
                ->resize(3000, null, function ($constraint) {
                    $constraint->aspectRatio();
                })
                ->encode('jpg', 100);
            $thumbImg = Image::make($localPath)
                ->resize(512, null, function ($constraint) {
                    $constraint->aspectRatio();
                })
                ->encode('jpg', 100);
            $imgLocation = Storage::disk('static')->put($filename, $img);
            $thumbLocation = Storage::disk('static')->put($thumbnailName, $thumbImg);
            $size_before = Storage::disk('static')->size($filename);
            $thumb_size_before = Storage::disk('static')->size($thumbnailName);
            ImageOptimizer::optimize(Storage::disk('static')->path($filename));
            ImageOptimizer::optimize(Storage::disk('static')->path($thumbnailName));
            $size_after = Storage::disk('static')->size($filename);
            $thumb_size_after = Storage::disk('static')->size($thumbnailName);
            $diff = $size_before - $size_after;
            $thumbDiff = $thumb_size_before - $thumb_size_after;
            $this->line('Filesize before: ' . $size_before);
            $this->line('Filesize after: ' . $size_after);
            $this->line('Thumb Filesize before: ' . $thumb_size_before);
            $this->line('Thumb Filesize after: ' . $thumb_size_after);
        }
    }

    private function checkExistingFilename($name) {
        $checkArtwork = Artwork::where('filename', $name . '.jpg')->count();
        return $checkArtwork;
    }

    private function uniqueName($episode, $user, $missingArtwork) {
        $i = 0;
        $uniqueFilename = $episode->episode_date->format('Y/m/') . Str::slug($user->artists->first()->name . '-' . $missingArtwork->title) . '_' . $missingArtwork->id;
        $exists = $this->checkExistingFilename($uniqueFilename);
        if (!$exists) {
            return $uniqueFilename;
        }
        while(!$exists) {
            $i++;
            $uniqueFilename = $uniqueFilename . '_v' . $i;
            $exists = $this->checkExistingFilename($uniqueFilename);
        }
        return $uniqueFilename;
    }
}