<?php

namespace App\Console\Commands;

use App\Home;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Storage;

class DownloadImageCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'app:downloadimage {id}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Download pictures of a given home';

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

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $id = $this->argument('id');
        $this->info(sprintf('Downloading images from home id = %s', $id));
        $home = Home::where('id', $id)->first();
        if (!$home instanceof Home) {
            $this->error(sprintf('No home with id «%s»', $id));
            return 1;
        }
        if ($home->pictures_downloaded) {
            $this->error(sprintf('Pictures already downloaded for «%s»', $id));
            return 1;
        }
        $pictures = $home->pictures;
        $newPictures = [];
        $countPictures = count($pictures);
        $this->info(sprintf('Downloading %u images', $countPictures));
        foreach ($pictures as $picture) {
            $picture_content = file_get_contents($picture);
            $newPicture = sprintf('%s/%s', $id, basename($picture));
            if (false === Storage::put($newPicture, $picture_content, 'public')) {
                $this->error(sprintf('Can\'t store «%s» into «%s»', $picture, $newPicture));
                return 1;
            }
            $newPictures[] = sprintf('/storage/%s', $newPicture);
            sleep(1);
        }

        $home->pictures = $newPictures;
        $home->pictures_downloaded = true;
        $home->save();
        $this->info('Download finished');

        return 0;
    }
}