<?php

namespace Cobblestone\CcLogin\Helper;

use Doctrine\Common\Collections\ArrayCollection;

class TenantCollection extends ArrayCollection
{
    /**
     * @param int $unikLeaseNumber
     * @param int $tenancyNumber
     * @param bool $onlyLegalTenants
     * @return TenantCollection
     */
    public function getByTenancyIdentifier(int $unikLeaseNumber, int $tenancyNumber, bool $onlyLegalTenants = false): TenantCollection
    {
        $tenants = $this->filter(function (array $tenant) use ($unikLeaseNumber, $tenancyNumber) {
            return (int) $this->getTenancy($tenant)["number"] === $tenancyNumber && (int) $this->getLease($tenant)["unik_lease_number"] === $unikLeaseNumber;
        });

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

        return $tenants;
    }

    /**
     * @return TenantCollection
     */
    public function sortByTenancyIdentifier(): TenantCollection
    {
        $tenants = $this->getValues();

        usort($tenants, function ($a, $b) {
            $diff = $this->compareLeaseNumber($a, $b);

            return ($diff !== 0) ? $diff : $this->compareTenancyNumber($a, $b);
        });

        return new TenantCollection($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 $a
     * @param array $b
     * @return int
     */
    private function compareLeaseNumber(array $a, array $b): int
    {
        return $this->getLease($a)["unik_lease_number"] - $this->getLease($b)["unik_lease_number"];
    }

    /**
     * @param array $a
     * @param array $b
     * @return int
     */
    private function compareTenancyNumber(array $a, array $b): int
    {
        return $this->getTenancy($a)["number"] - $this->getTenancy($b)["number"];
    }

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

    /**
     * @param array $tenant
     * @return array
     */
    private function getLease(array $tenant): array
    {
        return $this->getTenancy($tenant)["lease"];
    }
}