<?php

namespace App\Imports;

use App\Models\Asset;
use App\Models\Registries\Registry;
use App\Models\Registries\RegistryType;
use App\Services\FileDownloadService;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithHeadingRow;

class NtdRegistryImport extends Import implements ToCollection, WithHeadingRow {
    public Registry $registry;

    public array $mapper = [
        'name' => ['prop' => 'name', 'required' => true],
        'link' => ['prop' => 'link'],
        'active_since' => ['prop' => 'active_since', 'date' => true],
        'active_till' => ['prop' => 'active_till', 'date' => true],
        'category' => ['prop' => 'cat_name', 'required' => true],
        'type' => ['prop' => 'type'],
        'agency' => ['prop' => 'agency']
    ];


    public function __construct() {
        $this->registry = Registry::query()->where(['type' => RegistryType::NTD])->first();
    }

    public function collection(Collection $collection) {
        $collection->each(function($row) use(&$data) {
            if ($row = $this->mapData($row)) {
                $this->importRow($row);
            }
        });
    }

    public function importRow($row) {
        $category = $this->registry->categories()->firstOrCreate(['name' => $row['category']]);
        $entry = $this->registry->entries()->firstOrCreate(['name' => $row['name'], 'category_id' => $category->id ?? 0]);
        $active_since = (is_object($row['active_since'] ?? null)) ? $row['active_since'] : null;
        $active_till = (is_object($row['active_till'] ?? null)) ? $row['active_till'] : null;
        $asset = $this->download($row['link'] ?? null);
        $link = $this->checkLink($row['link']);
        $entry->update(['active_since' => $active_since, 'active_till' => $active_till, 'asset_id' => $asset->id ?? null, 'link' => $link]);
        $entry->properties->setValues(['normative-document-type' => ['title' => $row['type'] ?? null], 'host-agency' => ['title' => $row['agency'] ?? null]]);
    }

    public function download($url): ?Asset {
        return (new FileDownloadService())->download($url, 'registries/ntd');
    }

    public function checkLink($link) {
        $ext = pathinfo($link, PATHINFO_EXTENSION);
        $host = parse_url($link, PHP_URL_HOST);
        $result = null;
        if ($ext !== 'pdf') {
            if ($host && !in_array($host, ['faufcc.ru', 'www.faufcc.ru'])) $result = $link;
        }echo ("{$result}\n");
        return $result;
    }


}
