<?php

namespace App\Console\Commands;

use App\Models\Storage;
use Illuminate\Console\Command;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Create Server and update';

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

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $hostname = env("APP_SERVER");
        if($hostname === false) {
            $this->info("Can't get hostname");
            return self::FAILURE;
        }

        //Used cache
        $size = $this->getUsedCached();

        $server = \App\Models\Server::query()->where("servername", "=", $hostname)->first();

        if(is_null($server)) {
            $server = new \App\Models\Server();
            $server->servername = $hostname;
            $server->storage = disk_free_space(storage_path("cache")) - (1024*1000000) + $size;
        }
        $server->last_seen = date("Y-m-d H:i:s");
        $server->userd = $size;
        $server->saveOrFail();


        return 0;
    }

    private function getUsedCached() {
        $r = \Illuminate\Support\Facades\Storage::disk("cache")->allFiles();
        $size = 0;
        foreach ($r as $item) {
            $size += \Illuminate\Support\Facades\Storage::disk("cache")->size($item);
        }
        return $size;
    }
}
