<?php

class ServiceProvider extends CComponent
{
  private $services;
  private $servicesByStatus;

  private $errorMessages = null;

  public function __construct($services)
  {
    $this->services = $services;
    $this->servicesByStatus = $this->groupByStatus($this->services);
  }

  public function getIsEmpty()
  {
    return count($this->services)== 0;
  }

  public function getService()
  {
    $this->validate();
    if ($this->invalid() || $this->isEmpty)
      return null;

    return $this->services[0];
  }

  public function valid()
  {
    return count($this->errors)==0;
  }

  public function invalid()
  {
    return !$this->valid();
  }

  public function getErrors()
  {
    if (!isset($this->errorMessages))
      $this->validate();

    return $this->errorMessages;
  }

  // PRIVATE

  private function validate()
  {
    $this->errorMessages = array();

    if (! $this->validateUniqueStatus())
      $this->errorMessages[] = "There are more than one incomplete status for this gate group.";
    if (! $this->validateUniqueServicePerStatus()) 
      $this->errorMessages[] = "An incomplete status has more than one service for this gate group.";
  }

  private function validateUniqueStatus()
  {
    return count(array_keys($this->servicesByStatus))==1; 
  }

  private function validateUniqueServicePerStatus()
  {
    foreach($this->servicesByStatus as $status)
      if (count($status)>1)
        return false;

    return true;
  }

  private function groupByStatus($services)
  {
    return array_reduce($services, function(&$result, $service) {
      $result[$service->status][] = $service;
      return $result;
    }, array());
  }

}
