<?php

namespace App\Console\Commands;

use App\Jobs\SandownArticleImport;
use Illuminate\Console\Command;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
use Mtc\ContentManager\Models\ContentCategory;
use Mtc\MercuryDataModels\Template;

class SandownBlogImport extends Command
{
    use DispatchesJobs;

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'sandown:blog-import {category-slug? : The category slug}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Import news for Sandown';

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $this->info('Import started!');

        $category = null;
        $categorySlug = $this->argument('category-slug');
        if (!empty($categorySlug)) {
            $category = ContentCategory::where('slug', $categorySlug)->first();
        }

        $content = Storage::disk('file-storage')->get('sandown-news-export.csv');
        $file = storage_path('sandown-blog-import.csv');
        File::put($file, $content);

        $imagesContent = Storage::disk('file-storage')->get('sandown-images-import.csv');
        $imagesFile = storage_path('sandown-images-import.csv');
        File::put($imagesFile, $imagesContent);

        if (!file_exists($file)) {
            $this->error('File not found!');
            return self::FAILURE;
        }

        $row = 1;
        if (($handle = fopen($file, "r")) !== false) {
            $imagesLinks = $this->getImagesLinks($imagesFile);

            /** @var Template $template */
            $template = Template::query()
                ->where('slug', 'news-article')
                ->first();

            if (!$template) {
                $this->error('News article template not found');
                return self::FAILURE;
            }

            while (($data = fgetcsv($handle, 5000, ',', '"', '"')) !== false) {
                if ($data[0] == 'name') {
                    continue;
                }

                $this->dispatch(new SandownArticleImport($data, $imagesLinks, $template, $category));
                $row++;
            }
            fclose($handle);
        }

        $this->info('Imported ' . $row . ' records!');
        $this->info('Import finished!');

        return self::SUCCESS;
    }


    private function getImagesLinks($imagesFile): array
    {
        if (!file_exists($imagesFile)) {
            return [];
        }

        $imagesLinks = [];

        if (($imagesHandle = fopen($imagesFile, "r")) !== false) {
            while (($imagesData = fgetcsv($imagesHandle, 1000, ',', '"', '"')) !== false) {
                if ($imagesData[0] == 'id') {
                    continue;
                }

                $imagesLinks[$imagesData[0]] = $imagesData[1];
            }
        }

        return $imagesLinks;
    }
}
