<?php

declare(strict_types=1);

/*
 * Copyright (c) 2023-2024 François Kooman <fkooman@tuxed.net>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

namespace fkooman\Radius;

class RadiusPacket
{
    public const ACCESS_REQUEST = 1;
    public const ACCESS_ACCEPT = 2;
    public const ACCESS_REJECT = 3;
    public const ACCESS_CHALLENGE = 11;

    private const PACKET_TYPE_TO_STRING = [
        self::ACCESS_REQUEST => 'Access-Request',
        self::ACCESS_ACCEPT => 'Access-Accept',
        self::ACCESS_REJECT => 'Access-Reject',
        self::ACCESS_CHALLENGE => 'Access-Challenge',
    ];

    private int $packetType;
    private int $packetId;
    private string $packetAuthenticator;
    private AttributeCollection $attributeCollection;

    public function __construct(int $packetType, int $packetId, ?string $packetAuthenticator = null)
    {
        $this->packetType = Utils::verifyPacketType($packetType);
        $this->packetId = Utils::requireRange($packetId, 0, 255);
        $packetAuthenticator ??= random_bytes(16);
        $this->packetAuthenticator = Utils::requireLength($packetAuthenticator, 16);
        $this->attributeCollection = new AttributeCollection();
    }

    public function __clone()
    {
        $this->attributeCollection = clone $this->attributeCollection;
    }

    public function __toString(): string
    {
        return sprintf(
            'RADIUS PACKET: TYPE=%s ID=%d AUTHENTICATOR=0x%s',
            $this->packetType(),
            $this->packetId(),
            Utils::hexEncode($this->packetAuthenticator)
        );
    }

    public function packetType(): string
    {
        return self::PACKET_TYPE_TO_STRING[$this->packetType];
    }

    public function isResponse(): bool
    {
        return $this->isAccessAccept() || $this->isAccessReject() || $this->isAccessChallenge();
    }

    public function isAccessRequest(): bool
    {
        return self::ACCESS_REQUEST === $this->packetType;
    }

    public function isAccessAccept(): bool
    {
        return self::ACCESS_ACCEPT === $this->packetType;
    }

    public function isAccessReject(): bool
    {
        return self::ACCESS_REJECT === $this->packetType;
    }

    public function isAccessChallenge(): bool
    {
        return self::ACCESS_CHALLENGE === $this->packetType;
    }

    public function packetId(): int
    {
        return $this->packetId;
    }

    public function packetAuthenticator(): string
    {
        return $this->packetAuthenticator;
    }

    public function setPacketAuthenticator(string $packetAuthenticator): void
    {
        $this->packetAuthenticator = Utils::requireLength($packetAuthenticator, 16);
    }

    public function attributeCollection(): AttributeCollection
    {
        return $this->attributeCollection;
    }

    public function setAttributeCollection(AttributeCollection $attributeCollection): void
    {
        $this->attributeCollection = $attributeCollection;
    }

    public function toBytes(): string
    {
        $attributeData = $this->attributeCollection->toBytes();

        return chr($this->packetType) . chr($this->packetId) . Utils::shortToBytes(20 + strlen($attributeData)) . $this->packetAuthenticator . $attributeData;
    }

    public static function fromBytes(string $radiusPacketData): self
    {
        // make sure the length of the RADIUS packet matches the length of the
        // data we received and is at most 4096 octets
        $packetLength = Utils::requireRange(Utils::bytesToShort(Utils::safeSubstr($radiusPacketData, 2, 2)), 20, 4096);
        $radiusPacketData = Utils::requireLength($radiusPacketData, $packetLength);

        $radiusPacket = new self(
            ord(Utils::safeSubstr($radiusPacketData, 0, 1)),
            ord(Utils::safeSubstr($radiusPacketData, 1, 1)),
            Utils::safeSubstr($radiusPacketData, 4, 16)
        );

        if (20 < strlen($radiusPacketData)) {
            $radiusPacket->setAttributeCollection(AttributeCollection::fromBytes(Utils::safeSubstr($radiusPacketData, 20)));
        }

        return $radiusPacket;
    }
}
