<?php

namespace App\Download;

use Aimeos\Map;
use App\Torrentio\Result\TorrentioResult;
use App\User\Dto\UserPreferences;

class DownloadOptionEvaluator
{
    /**
     * @param TorrentioResult[] $results
     * @param UserPreferences $filter
     * @return TorrentioResult|null
     * @throws \Throwable
     */
    public function evaluateOptions(array $results, UserPreferences $filter): ?TorrentioResult
    {
        $matches = Map::from($results)->filter(function ($result) use ($filter) {
            if (false === $this->validateFilterItems($result, $filter)) {
                return false;
            }

            // todo: This is arbitrary- revisit in the future
            //if (false === $this->validateSize($result, $filter)) {
            //    return false;
            //}

//            if (false === $this->validateDownloadUrl($result->url)) {
//                return false;
//            }

            return true;
        });

//        dd($filter);

        if ($matches->count() > 0) {
            return Map::from($matches)->usort(fn($a, $b) => $a->seeders <=> $b->seeders)->last();
        }

        return null;
    }

    private function validateFilterItems(TorrentioResult $result, UserPreferences $filter): bool
    {
        if (array_intersect($filter->language, $result->languages) === []) {
            return false;
        }

        $valid = true;

        if (null !== $filter->resolution && !in_array($result->resolution, $filter->resolution)) {
            $valid = false;
        }

        if (null !== $filter->codec && !in_array($result->codec, $filter->codec)) {
            $valid = false;
        }

        if (null !== $filter->quality && !in_array($result->quality, $filter->quality)) {
            $valid = false;
        }

        if (null !== $filter->provider && !in_array($result->provider, $filter->provider)) {
            $valid = false;
        }

        return $valid;
    }

    private function validateSize(TorrentioResult $result, UserPreferences $filter): bool
    {
        $sizeLow = 000;
        $sizeHigh = 4096;

        if (str_contains($result->size, 'GB')) {
            $size = (int) trim(str_replace('GB', '', $result->size)) * 1024;
        } else {
            $size = (int) trim(str_replace('MB', '', $result->size));
        }

        if ($size > $sizeLow && $size < $sizeHigh) {
            return true;
        }

        return false;
    }

    public function validateDownloadUrl(string $downloadUrl)
    {
        $badFileLocations = [
            'https://torrentio.strem.fun/videos/failed_infringement_v2.mp4' => 'Removed for Copyright Infringement.',
            'https://torrentio.strem.fun/videos/downloading_v2.mp4' => 'Your torrent is downloading to your debrid provider.'
        ];

        $headers = get_headers($downloadUrl, true);
        if (array_key_exists($headers['Location'], $badFileLocations)) {
            return false;
        }

        return true;
    }
}
