<?php


namespace Shop\Domain\Basket;


use Repo\Concrete\AbstractEntity;
use Shop\Domain\Basket\Contracts\BasketEntityInterface;
use Shop\Domain\Customer\Contracts\CustomerEntityInterface;

class BasketEntity extends AbstractEntity implements BasketEntityInterface
{

    /**
     * @var CustomerEntityInterface
     */
    protected $customer;

    protected $items = [];


    /**
     * @var string
     */
    protected $name;

    /**
     * @return string
     */
    public function getName(): string
    {
        return $this->name;
    }

    /**
     * @param string $name
     * @return BasketEntity
     */
    public function setName(string $name): BasketEntity
    {
        $this->name = $name;
        return $this;
    }


    /**
     * @return array
     */
    public function getItems(): array
    {
        return $this->items;
    }

    public function addItem(BasketItem $item): void
    {
        $this->items[] = $item;
    }

    /**
     * @param array $items
     * @return BasketEntity
     */
    public function setItems(array $items): BasketEntity
    {
        $this->items = $items;
        return $this;
    }

    /**
     * @return CustomerEntityInterface
     */
    public function getCustomer(): CustomerEntityInterface
    {
        return $this->customer;
    }

    /**
     * @param CustomerEntityInterface $customer
     * @return BasketEntity
     */
    public function setCustomer(CustomerEntityInterface $customer): BasketEntity
    {
        $this->customer = $customer;
        return $this;
    }

    /**
     * @return int
     */
    public function getCount(): int
    {
        $s = 0;
        foreach ($this->items as $item) {
            $s += $item->getAmount();
        }
        return $s;
    }

    /**
     * @return float
     */
    public function getSum(): float
    {
        $summ = 0;

        foreach ($this->items as $item) {
            $price = (int)$item->getAmount() * (float)$item->getPrice();
            $summ += $price;
        }

        return $summ;
    }


    /**
     * @param string $ref
     * @return int
     */
    public function itemExistByRef(string $ref): int
    {
        foreach ($this->items as $item) {
            if ($item->getRef() === $ref) {
                return $item->getAmount();
            }
        }
        return 0;
    }

    public function clear(): void
    {
        throw new \RuntimeException('clear not implementation');
    }

}