<?php
namespace Fifa\ConnectId\Sdk\Model;

use Fifa\ConnectId\Sdk\Api\Model\PersonType;
use Fifa\ConnectId\Sdk\Util\ArrayUtils\ArrayParser;
use Fifa\ConnectId\Sdk\Util\ArrayUtils\DuplicatesFilter\PersonNameDuplicatesFilter;
use InvalidArgumentException;

/**
 * Class PersonData
 * @package Fifa\ConnectId\Sdk\Model
 */
class PersonData
{
    /**
     * @var PersonType
     */
    private $personType;

    /**
     * @var PersonName[]
     */
    private $personNames;

    /**
     * PersonData constructor.
     * @param PersonType $personType
     * @param PersonName[]|PersonName $personNames
     */
    public function __construct(PersonType $personType, $personNames)
    {
        $this->personType = $personType;
        $this->personNames = $this->parsePersonNames(is_array($personNames) ? $personNames : array($personNames));
    }

    /**
     * String representation of the object
     *
     * @return string
     */
    public function __toString()
    {
        $names = array();
        foreach ($this->personNames as $name) {
            $names[] = $name->__toString();
        }
        return join(', ', $names) . ' (' . $this->personType->getDateOfBirth()->format('Y-m-d') . ')';
    }

    /**
     * Gets person type
     *
     * @return PersonType
     */
    public function getPersonType(): PersonType
    {
        return $this->personType;
    }

    /**
     * Gets person names array
     *
     * @return PersonName[]
     */
    public function getPersonNames(): array
    {
        return $this->personNames;
    }

    /**
     * @param array $personNames
     * @return PersonName[]
     * @throws InvalidArgumentException
     */
    private function parsePersonNames(array $personNames): array
    {
        return
            ArrayParser::create($personNames)
                ->checkNotEmpty('Please provide at least one PersonName')
                ->checkContainsOnlyInstancesOf(PersonName::class)
                ->removeDuplicates(new PersonNameDuplicatesFilter())
                ->getData();
    }
}