<?php

use Illuminate\Console\Command;

//Use Band;

class RegenerateImages extends Command {

    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'images:regenerateThumbnails';
    protected $conn;

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Regenerates the bands thumbnails based on the main image.';

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

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function fire() {
        
        set_time_limit(0);
        ini_set('memory_limit', '-1');

        $connection = $this->ask('Please insert the connection (pt, es, pt-BR)');
        Config::set('database.default', $connection);

        $limit = 10;
        $offset = 0;
        //get the media that is unused in associations

        $continue = true;
        $cont = 0;
        while ($continue) {
            $this->info('Getting more bands. Offset '.$offset);
            $bands = Band::skip($offset)->take($limit)->get();

            if ($bands->isEmpty()) {
                $continue = false;
                break;
            }

            foreach ($bands as $band) {
                $this->info('Processing band '.$band->name);
                //check if band has an image
                if (!$band->hasMedia('image')) {
                    continue;
                }
                $imageUrl =$band->mediaPath('image');
                $imagePath = str_replace(url(), public_path(), $imageUrl);
                if (!file_exists($imagePath)){
                    $this->error('The main image '.$imagePath .' does not exist. Skipping');
                    continue;
                }
                
                if (!$band->hasMedia('thumbnail')) {
                    $band->generateImageType('thumbnail');
                }else{
                    $this->info('Band '.$band->name.' has a thumbnail. Skipping');
                }
                if (!$band->hasMedia('tiny-thumbnail')) {
                    $band->generateImageType('tiny-thumbnail');
                }else{
                    $this->info('Band '.$band->name.' has a tiny thumbnail. Skipping');
                }
            }
            $cont +=1;
            $offset = $cont*$limit;
        }
    }

    /**
     * Get the console command arguments.
     *
     * @return array
     */
    protected function getArguments() {
        return [];
    }

    /**
     * Get the console command options.
     *
     * @return array
     */
    protected function getOptions() {
        return [];
    }

}
