<?php

use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
use Illuminate\Support\Facades\DB;

class FixImages extends Command {

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Removes unused band media and deletes the files if they exist in the FS';

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

    protected function removeMedia($media) {
        //dd($media);
        //we have a media to delete

        $mediaId = $media->id;

        //remove the media record
        $this->info('Deleting unused media record from the database with id ' . $mediaId);
        $mediaDelQuery = 'delete from media where id = ? ';

        $statement = $this->conn->getPdo()->prepare($mediaDelQuery);
        $res = $statement->execute([$mediaId]);

        //remove the media file
        $filePath = $media->path;
        $fullFilePath = public_path() . '/' . $filePath;
        if (file_exists($fullFilePath)) {
            $this->info('Removing file ' . $fullFilePath);
            @unlink($fullFilePath);
        }
    }

    protected function removeMediaByArray($filesToDelete) {
        //dd($media);
        //we have a media to delete

        $mediaIdsArr = array_keys($filesToDelete);
        $mediaIdsStr = implode(',', $mediaIdsArr);
        //remove the media records
        $this->info('Deleting unused media record from the database with ids ' . $mediaIdsStr);
        $mediaDelQuery = "delete from media where id in ( ".$mediaIdsStr." )";
        $res = $this->conn->getPdo()->exec($mediaDelQuery);
        
        //res = $statement->execute([$mediaIdsStr]);

        //remove the media files
        foreach ($filesToDelete as $filePath) {
            $fullFilePath = public_path() . '/' . $filePath;
            if (file_exists($fullFilePath)) {
                $this->info('Removing file ' . $fullFilePath);
                @unlink($fullFilePath);
            }
        }
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function fire() {


        $connection = $this->ask('Please insert the database connection (pt, es, pt-BR)');

        $this->conn = DB::connection($connection);
        $limit = 1000;
        $offset = 0;
        //get the media that is unused in associations

        $continue = true;
        $cont = 0;
        while ($continue) {
            $this->info('Counter is '.$cont);
            $query = "select * from media
            where id not in (
            select media_id from media_associations 
            where media_Association_type = 'Band' and (position = 'image' or position = 'thumbnail' or position = 'tiny-thumbnail'))
            limit " . $limit . ' offset ' . $offset;
            $unusedMedia = $this->conn->select($query);
            if (empty($unusedMedia)) {
                $this->info('no more media...');
                break;
            }
            $filesToDelete = [];
            foreach ($unusedMedia as $media) {
                $filesToDelete[$media->id] = $media->path;
            }
            $this->removeMediaByArray($filesToDelete);
            $cont ++;
        }
    }

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

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

}
