<?php

namespace App\Console\Commands;

use App\Helper\Image;
use App\Helper\ImagePreparation;
use App\Http\Controllers\PublicController;
use App\Models\Storage;
use App\Models\Theme;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class ServerUpdateCache extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'server:update-cache';

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

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle(Image $image)
    {
        $themeList = [];
        $themesModel = Theme::query()->where("typ", "=", "gallery")->get();
        foreach ($themesModel as $tm) {
            $themeList[$tm->name] = $tm;
        }

        $sql = 'SELECT images.id, images.path, images.driver, tenants.template, tenants.gallery_default_theme FROM images LEFT JOIN tenants ON tenants.id = images.tenant WHERE typ != "watermark" AND  servername = "'.env("APP_SERVER").'";';
        $res = DB::select($sql);
        foreach ($res as $re) {
            $this->info("Image: ".$re->id);
            $theme = $themeList[$re->gallery_default_theme];
            if(is_null($theme)) {
                $this->info("Error Theme not found: ".$re->template);
                exit();
                continue;
            }
            if($theme->img_pixel) {
                $image->getImageById($re->id, PublicController::$size["pixel"]);
            }
            if($theme->img_small) {
                $image->getImageById($re->id, PublicController::$size["small"]);
            }
            if($theme->img_medium) {
                $image->getImageById($re->id, PublicController::$size["medium"]);
            }
            if($theme->img_big) {
                $image->getImageById($re->id, PublicController::$size["big"]);
            }
        }

        $list = \Illuminate\Support\Facades\Storage::disk("cache")->allFiles("");
        foreach($list as $l) {
            if(preg_match("@^\d*_orginal_@", $l)) {
                \Illuminate\Support\Facades\Storage::disk("cache")->delete($l);
                //$this->info("To Delete: ".$l);
            }
        }


    }
}
