<?php

namespace Velis\Dojo;

use ArrayAccess;
use ArrayIterator;
use Countable;
use InvalidArgumentException;
use IteratorAggregate;
use RuntimeException;
use Traversable;
use Velis\Model\DataObject;
use Velis\Output;

/**
 * dojo.data support for Velis Framework
 *
 * @uses       ArrayAccess
 * @uses       IteratorAggregate
 * @uses       Countable
 */
class Data implements ArrayAccess, IteratorAggregate, Countable
{
    /**
     * Identifier field of item
     * @var string|int
     */
    protected $_identifier;


    /**
     * Collected items
     * @var array
     */
    protected $_items = [];


    /**
     * Label field of item
     * @var string
     */
    protected $_label;


    /**
     * Data container metadata
     * @var array
     */
    protected $_metadata = [];


    /**
     * Unfiltered flag
     * @var bool
     */
    protected $_unfiltered = false;


    /**
     * Constructor
     *
     * @param string|null $identifier
     * @param array|Traversable|null $items
     * @param string|null $label
     * @param bool $stringifyKeys
     */
    public function __construct($identifier = null, $items = null, $label = null, $stringifyKeys = false)
    {
        if ($stringifyKeys && $identifier && $items) {
            foreach ($items as $item) {
                $item[$identifier] = (string)$item[$identifier];
            }
        }
        if (null !== $identifier) {
            $this->setIdentifier($identifier);
        }
        if (null !== $items) {
            $this->setItems($items);
        }
        if (null !== $label) {
            $this->setLabel($label);
        }
    }


    /**
     * Sets datastore to return unfiltered items
     * @param bool $unfiltered
     * @return $this
     */
    public function unfiltered($unfiltered = true)
    {
        $this->_unfiltered = $unfiltered;

        return $this;
    }


    /**
     * Set the items to collect
     * @param array|Traversable $items
     * @return $this
     */
    public function setItems($items)
    {
        $this->clearItems();

        return $this->addItems($items);
    }


    /**
     * Set an individual item, optionally by identifier (overwrites)
     * @param array|object $item
     * @param string|null $id
     * @return $this
     */
    public function setItem($item, $id = null)
    {
        $item = $this->_normalizeItem($item, $id);
        $this->_items[$item['id']] = $item['data'];

        return $this;
    }


    /**
     * Add an individual item, optionally by identifier
     * @param array|object $item
     * @param string|null $id
     * @return $this
     */
    public function addItem($item, $id = null)
    {
        $item = $this->_normalizeItem($item, $id);

        if ($this->hasItem($item['id'])) {
            throw new InvalidArgumentException('Overwriting items using addItem() is not allowed');
        }

        $this->_items[$item['id']] = $item['data'];

        return $this;
    }


    /**
     * Add multiple items at once
     * @param array|Traversable $items
     * @return $this
     */
    public function addItems($items)
    {
        if (!is_array($items) && (!is_object($items) || !($items instanceof Traversable))) {
            throw new InvalidArgumentException('Only arrays and Traversable objects may be added to ' . __CLASS__);
        }

        foreach ($items as $item) {
            $this->addItem($item);
        }

        return $this;
    }


    /**
     * Get all items as an array
     *
     * Serializes items to arrays.
     *
     * @return array
     */
    public function getItems()
    {
        return $this->_items;
    }


    /**
     * Does an item with the given identifier exist?
     *
     * @param string|int $id
     * @return bool
     */
    public function hasItem($id)
    {
        return array_key_exists($id, $this->_items);
    }


    /**
     * Retrieve an item by identifier
     *
     * Item retrieved will be flattened to an array.
     *
     * @param  string $id
     * @return array
     */
    public function getItem($id)
    {
        if (!$this->hasItem($id)) {
            return null;
        }

        return $this->_items[$id];
    }


    /**
     * Remove item by identifier
     * @param string $id
     * @return $this
     */
    public function removeItem($id)
    {
        if ($this->hasItem($id)) {
            unset($this->_items[$id]);
        }

        return $this;
    }


    /**
     * Remove all items at once
     * @return $this
     */
    public function clearItems()
    {
        $this->_items = [];

        return $this;
    }


    /**
     * Set identifier for item lookups
     *
     * @param string|int|null $identifier
     * @return $this
     */
    public function setIdentifier($identifier)
    {
        if (null === $identifier) {
            $this->_identifier = null;
        } elseif (is_string($identifier)) {
            $this->_identifier = $identifier;
        } elseif (is_numeric($identifier)) {
            $this->_identifier = (int) $identifier;
        } else {
            throw new InvalidArgumentException('Invalid identifier; please use a string or integer');
        }

        return $this;
    }


    /**
     * Retrieve current item identifier
     *
     * @return string|int|null
     */
    public function getIdentifier()
    {
        return $this->_identifier;
    }


    /**
     * Set label to use for displaying item associations
     * @param  string|null $label
     * @return $this
     */
    public function setLabel($label)
    {
        if (null === $label) {
            $this->_label = null;
        } else {
            $this->_label = (string) $label;
        }

        return $this;
    }


    /**
     * Retrieve item association label
     *
     * @return string|null
     */
    public function getLabel()
    {
        return $this->_label;
    }


    /**
     * Set metadata by key or en masse
     * @param string|array $spec
     * @param mixed $value
     * @return $this
     */
    public function setMetadata($spec, $value = null)
    {
        if (is_string($spec) && (null !== $value)) {
            $this->_metadata[$spec] = $value;
        } elseif (is_array($spec)) {
            foreach ($spec as $key => $value) {
                $this->setMetadata($key, $value);
            }
        }

        return $this;
    }


    /**
     * Get metadata item or all metadata
     * @param null|string $key Metadata key when pulling single metadata item
     * @return mixed
     */
    public function getMetadata($key = null)
    {
        if (null === $key) {
            return $this->_metadata;
        }

        if (array_key_exists($key, $this->_metadata)) {
            return $this->_metadata[$key];
        }

        return null;
    }


    /**
     * Clear individual or all metadata item(s)
     * @param null|string $key
     * @return $this
     */
    public function clearMetadata($key = null)
    {
        if (null === $key) {
            $this->_metadata = array();
        } elseif (array_key_exists($key, $this->_metadata)) {
            unset($this->_metadata[$key]);
        }

        return $this;
    }


    /**
     * Load object from array
     * @param array $data
     * @return $this
     */
    public function fromArray(array $data)
    {
        if (array_key_exists('identifier', $data)) {
            $this->setIdentifier($data['identifier']);
        }
        if (array_key_exists('label', $data)) {
            $this->setLabel($data['label']);
        }
        if (array_key_exists('items', $data) && is_array($data['items'])) {
            $this->setItems($data['items']);
        } else {
            $this->clearItems();
        }

        return $this;
    }


    /**
     * Load object from JSON
     * @param string $json
     * @return $this
     */
    public function fromJson($json)
    {
        if (!is_string($json)) {
            throw new InvalidArgumentException('fromJson() expects JSON input');
        }
        $data = Output::jsonDecode($json);

        return $this->fromArray($data);
    }


    /**
     * Serialize entire data structure, including identifier and label, to array
     * @return array
     */
    public function toArray()
    {
        if (null === ($identifier = $this->getIdentifier())) {
            throw new RuntimeException('Serialization requires that an identifier be present in the object; first call setIdentifier()');
        }

        $array = [
            'identifier' => $identifier,
            'items' => array_values($this->getItems()),
        ];

        $metadata = $this->getMetadata();
        if (!empty($metadata)) {
            foreach ($metadata as $key => $value) {
                $array[$key] = $value;
            }
        }

        if (null !== ($label = $this->getLabel())) {
            $array['label'] = $label;
        }

        return $array;
    }


    /**
     * Serialize to JSON (dojo.data format)
     *
     * @return string
     */
    public function toJson()
    {
        return Output::jsonEncode($this->toArray());
    }


    /**
     * Serialize to string (proxy to {@link toJson()})
     *
     * @return string
     */
    public function __toString()
    {
        return $this->toJson();
    }


    /**
     * ArrayAccess: does offset exist?
     *
     * @param  string|int $offset
     * @return bool
     */
    public function offsetExists($offset)
    {
        return (null !== $this->getItem($offset));
    }


    /**
     * ArrayAccess: retrieve by offset
     *
     * @param  string|int $offset
     * @return array
     */
    public function offsetGet($offset)
    {
        return $this->getItem($offset);
    }


    /**
     * ArrayAccess: set value by offset
     *
     * @param  string $offset
     * @param  array|object|null $value
     * @return void
     */
    public function offsetSet($offset, $value)
    {
        $this->setItem($value, $offset);
    }


    /**
     * ArrayAccess: unset value by offset
     *
     * @param  string $offset
     * @return void
     */
    public function offsetUnset($offset)
    {
        $this->removeItem($offset);
    }


    /**
     * IteratorAggregate: return an iterator
     *
     * @return Traversable
     */
    public function getIterator()
    {
        return new ArrayIterator($this->_items);
    }


    /**
     * Countable: how many items are present
     *
     * @return int
     */
    public function count()
    {
        return count($this->_items);
    }


    /**
     * Normalize an item to attach to the collection
     * @param array|object $item
     * @param string|int|null $id
     * @return array
     */
    protected function _normalizeItem($item, $id)
    {
        if (!is_object($item) && !is_array($item)) {
            throw new InvalidArgumentException('Only arrays and objects may be attached');
        }

        if (null === ($identifier = $this->getIdentifier())) {
            throw new RuntimeException('You must set an identifier prior to adding items');
        }

        if (is_object($item)) {
            if ($item instanceof DataObject) {
                $itemId = $item->id();
                $item = $item->getDataStoreItem($this->_unfiltered);

                if ($id && !is_array($itemId) && !array_key_exists($id, $item)) {
                    $item[$id] = $itemId;
                } elseif (is_array($itemId)) {
                    foreach ($itemId as $idField => $idFieldValue) {
                        if (!array_key_exists($idField, $item)) {
                            $item[$idField] = $idFieldValue;
                        }
                    }
                }
            } elseif (method_exists($item, 'toArray')) {
                $item = $item->toArray();
            } else {
                $item = get_object_vars($item);
            }
        }

        if ((null === $id) && !array_key_exists($identifier, $item)) {
            throw new InvalidArgumentException('Item must contain a column matching the currently set identifier');
        } elseif (null === $id) {
            $id = $item[$identifier];
        } else {
            $item[$identifier] = $id;
        }

        return [
            'id' => $id,
            'data' => $item,
        ];
    }
}
