<?php

namespace Cobblestone\CcLogin\Helper;

use Doctrine\Common\Collections\ArrayCollection;

class TenantCollection extends ArrayCollection
{
    /**
     * @param int $unikLeaseNumber
     * @param int $tenancyNumber
     * @return TenantCollection
     */
    public function getByComposite(int $unikLeaseNumber, int $tenancyNumber, bool $onlyLegalTenants = false): TenantCollection
    {
        $tenants = $this->filter(function (array $tenant) use ($unikLeaseNumber, $tenancyNumber) {
            $tenancy = $this->getTenancy($tenant);

            return (int) $tenancy["number"] === $tenancyNumber && (int) $tenancy["lease"]["unik_lease_number"] === $unikLeaseNumber;
        });

        if ($onlyLegalTenants) {
            $tenants = $tenants->getLegalTenants();
        }

        return $tenants;
    }

    /**
     * @param string $status
     * @return TenantCollection
     */
    public function getByStatus(string $status): TenantCollection
    {
        return $this->getByStatuses([$status]);
    }

    /**
     * @param array $statuses
     * @return TenantCollection
     */
    public function getByStatuses(array $statuses): TenantCollection
    {
        return $this->filter(function (array $tenant) use ($statuses) {
            $tenancy = $this->getTenancy($tenant);

            return in_array($tenancy["status"], $statuses);
        });
    }

    /**
     * @return TenantCollection
     */
    public function getLegalTenants(): TenantCollection
    {
        return $this->filter(function (array $tenant) {
            return $tenant["legal_tenant"];
        });
    }

    /**
     * @param array $tenant
     * @return array
     */
    private function getTenancy(array $tenant): array
    {
        return $tenant["tenancy"];
    }
}