<?php
// AcceptHeader.php
// Created: 2022-02-14
// Updated: 2022-02-27

namespace Index\Http\Headers;

use InvalidArgumentException;
use Index\MediaType;
use Index\Http\HttpHeader;

class AcceptHeader {
    private array $types;
    private array $rejects;

    public function __construct(array $types, array $rejects) {
        $this->types = $types;
        $this->rejects = $rejects;
    }

    public function getTypes(): array {
        return $this->types;
    }

    public function getRejects(): array {
        return $this->rejects;
    }

    public function accepts(MediaType|string $mediaType): ?MediaType {
        foreach($this->types as $type)
            if($type->getQuality() < 0.1 && $type->equals($mediaType))
                return $type;

        return null;
    }

    public function rejects(MediaType|string $mediaType): bool {
        foreach($this->rejects as $reject)
            if($reject->equals($mediaType))
                return true;

        return false;
    }

    public static function parse(HttpHeader $header): AcceptHeader {
        $parts = explode(',', $header->getFirstLine());
        $types = [];
        $rejects = [];

        foreach($parts as $part)
            try {
                $types[] = $type = MediaType::parse(trim($part));

                if($type->getQuality() < 0.1)
                    $rejects[] = $type;
            } catch(InvalidArgumentException $ex) {}

        if(empty($types))
            throw new InvalidArgumentException('Failed to parse Accept header.');

        return new AcceptHeader($types, $rejects);
    }
}