<?php

namespace LaraBB\Torrent\UI\Web\Requests;

use Illuminate\Contracts\Container\BindingResolutionException;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\RedirectResponse;
use LaraBB\Torrent\Tasks\FindTask;
use Rhilip\Bencode\TorrentFile;

/**
 *
 */
class StoreRequest extends FormRequest
{
    /**
     * @return mixed
     */
    public function authorize(): mixed
    {
        return $this->user()->isInGroup(['Member']);
    }

    /**
     * @return string[]
     */
    public function rules(): array
    {
        return [
            'torrent'     => 'required|mimetypes:application/x-bittorrent',
            'announceurl' => 'accepted',
            'infohash'    => 'accepted'
        ];
    }

    /**
     * @return array
     */
    public function messages(): array
    {
        return [
            'torrent.required'     => trans('Please select a torrent file.'),
            'torrent.mimetypes'    => trans('The file you tired to upload is not a torrent file.'),
            'announceurl.accepted' => trans('Your torrent has an invalid announce URL. Please use the one specified in this form.'),
            'infohash.accepted'    => trans('This torrent already exists in our database.')
        ];
    }

    /**
     * @param $keys
     * @return array
     * @throws BindingResolutionException
     */
    public function all($keys = null): array
    {
        return array_merge(parent::all($keys), array_merge(
            $this->validateTorrent()
        ));
    }

    /**
     * @param $uuid
     * @return RedirectResponse
     */
    public function success($uuid): RedirectResponse
    {
        return redirect()->route('torrent.upload', [$uuid])->with([
            'success' => 'Your torrent was successfully uploaded. Please redownload it from here in order to start seeding.'
        ]);
    }

    /**
     * @return RedirectResponse
     */
    public function failed(): RedirectResponse
    {
        return redirect()->route('torrent.upload')->withInput()->with([
            'error' => trans('Your torrent could not be uploaded due to technical issues.')
        ]);
    }

    /**
     * @return array|true[]
     * @throws BindingResolutionException
     */
    private function validateTorrent(): array
    {
        $torrentFile = TorrentFile::load($this->file('torrent'));
        if(config('tracker.announce') != $torrentFile->getAnnounce()) {
            return [
                'announceurl' => false,
                'infohash'    => true,
            ];
        }

        $torrentFindTask = app()->make(FindTask::class);
        $torrent         = $torrentFindTask->byInfoHash($torrentFile->getInfoHash());
        if(!is_null($torrent)) {
            return [
                'announceurl' => true,
                'infohash'    => false,
            ];
        }

        return [
            'announceurl' => true,
            'infohash'    => true,
        ];
    }
}
