<?php

namespace AuthStack\OAuth2\Model\Protocol\Response\AuthorizationCode;

use Illuminate\Http\Request;
use AuthStack\OAuth2\Model\Protocol\Response\AbstractResponse;

class AuthorizationResponse extends AbstractResponse
{
    public function __construct(string $code = null)
    {
        $this->model['code'] = $code ?? str_random(16);
    }

    /**
     * @return array
     */
    public function model(): array
    {
        return [
            'code', 'state'
        ];
    }

    /**
     * @param Request|null $request
     * @return AuthorizationResponse
     */
    public function receive(Request $request = null): self
    {
        $request = $request ?? Request::createFromGlobals();

        $collection = collect();

        collect($this->model())->map(function($value) use ($collection, $request)
        {
            $collection->put($value, $request->input($value));
        });

        return $this->setModel($collection->toArray());
    }

    public function setCode(string $code)
    {
        return $this->setProperty('code', $code);
    }

    /**
     * @return mixed|null
     */
    public function getCode()
    {
        return $this->getProperty('code');
    }

    /**
     * @param string $scope
     * @return AbstractResponse
     */
    public function setState(string $scope)
    {
        return $this->setProperty('state', $scope);
    }

    /**
     * @return mixed|null
     */
    public function getState()
    {
        return $this->getProperty('state');
    }

    /**
     * This returns ['code' => 'random data', 'scope' => 'something, if specified in request']
     *
     * @return array
     */
    public function toArray(): array
    {
        $result = collect($this->model)->reject(function($value, $item)
        {
            return empty($value);
        });

        return $result->toArray();
    }
}