<?php

namespace LaraBB\Tracker\Traits;

use LaraBB\Tracker\UI\Web\Requests\Announce;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use stdClass;

trait SetCurrentRequestTrait
{
    /**
     * @param Announce $objRequest
     * @return stdClass
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function setCurrentRequest(Announce $objRequest): stdClass
    {
        $request = new stdClass();

        $request->pid        = $objRequest->route('pid');
        $request->peerId     = bin2hex($objRequest->get('peer_id'));
        $request->agent      = $objRequest->server('HTTP_USER_AGENT');
        $request->ip         = long2ip(ip2long($objRequest->ip()));
        $request->ipOverride = $objRequest->get('ip', $objRequest->get('ipv6'));
        $request->host       = gethostbyaddr($request->ipOverride);
        $request->infoHash   = bin2hex($objRequest->get('info_hash'));
        $request->port       = intval($objRequest->get('port'));
        $request->uploaded   = floatval($objRequest->get('uploaded'));
        $request->downloaded = floatval($objRequest->get('downloaded'));
        $request->left       = floatval($objRequest->get('left'));
        $request->event      = $objRequest->get('event');
        $request->numWant    = $objRequest->get('numwant', 30);
        $request->compact    = $objRequest->has('compact');
        $request->ip         = !empty($request->ipOverride) ? $request->ipOverride : $request->ip;
        $request->host       = $request->host == $request->ipOverride ? 'AA' : strtoupper($request->host);
        $request->compactStr = str_pad(pack('Nn', ip2long($request->ip), $request->port), 6);

        preg_match('/^(.+)\.([A-Z]{2,3})$/', $request->host, $tldm);
        $request->dns = isset($tldm[2]) && !empty($tldm[2]) ? $tldm[2] : 'AA';

        return $request;
    }
}
