<?php

namespace Velis\Config;

use Exception;
use InvalidArgumentException;
use Iterator;

/**
 * Config base with sections handling
 * @author Olek Procki <olo@velis.pl>
 */
class Config implements ConfigInterface, Iterator
{
    /**
     * Whether in-memory modifications to configuration data are allowed
     *
     * @var bool
     */
    protected $_allowModifications;


    /**
     * Iteration index
     *
     * @var int
     */
    protected $_index;


    /**
     * Number of elements in configuration data
     *
     * @var int
     */
    protected $_count;


    /**
     * Contains array of configuration data
     *
     * @var array
     */
    protected $_data;


    /**
     * Used when unsetting values during iteration to ensure we do not skip
     * the next element
     *
     * @var bool
     */
    protected $_skipNextIteration;


    /**
     * Contains which config file sections were loaded. This is null
     * if all sections were loaded, a string name if one section is loaded
     * and an array of string names if multiple sections were loaded.
     *
     * @var mixed
     */
    protected $_loadedSection;


    /**
     * This is used to track section inheritance. The keys are names of sections that
     * extend other sections, and the values are the extended sections.
     *
     * @var array
     */
    protected $_extends = array();


    /**
     * Internal error messages
     *
     * @var null|array
     */
    protected $_errorMessages = array();


    /**
     * Velis\Config provides a property based interface to
     * an array. The data are read-only unless $allowModifications
     * is set to true on construction.
     *
     * Velis\Config also implements Countable and Iterator to
     * facilitate easy access to the data.
     *
     * @param array $array
     * @param bool $allowModifications
     * @return void
     */
    public function __construct(array $array, $allowModifications = false)
    {
        $this->_allowModifications = (bool) $allowModifications;
        $this->_loadedSection = null;
        $this->_index = 0;
        $this->_data = array();
        foreach ($array as $key => $value) {
            if (is_array($value)) {
                $this->_data[$key] = new self($value, $this->_allowModifications);
            } else {
                $this->_data[$key] = $value;
            }
        }
        $this->_count = count($this->_data);
    }

    /**
     * {@inheritDoc}
     */
    public function get(string $key, $default = null, string $cast = null)
    {
        $result = $default;
        if (array_key_exists($key, $this->_data)) {
            $result = $this->_data[$key];
        }

        return $result;
    }

    /**
     * Magic function so that $obj->value will work.
     *
     * @param string $name
     * @return mixed
     */
    public function __get($name)
    {
        return $this->get($name);
    }


    /**
     * Only allow setting of a property if $allowModifications
     * was set to true on construction. Otherwise, throw an exception.
     *
     * @param  string $name
     * @param  mixed  $value
     * @throws Exception
     * @return void
     */
    public function __set($name, $value)
    {
        if ($this->_allowModifications) {
            if (is_array($value)) {
                $this->_data[$name] = new self($value, true);
            } else {
                $this->_data[$name] = $value;
            }
            $this->_count = count($this->_data);
        } else {
            throw new InvalidArgumentException('Velis\Config is read only');
        }
    }


    /**
     * Deep clone of this instance to ensure that nested Velis\Configs
     * are also cloned.
     *
     * @return void
     */
    public function __clone()
    {
        $array = array();
        foreach ($this->_data as $key => $value) {
            if ($value instanceof Config) {
                $array[$key] = clone $value;
            } else {
                $array[$key] = $value;
            }
        }
        $this->_data = $array;
    }


    /**
     * Return an associative array of the stored data.
     *
     * @return array
     */
    public function toArray()
    {
        $array = array();
        $data = $this->_data;
        foreach ($data as $key => $value) {
            if ($value instanceof Config) {
                $array[$key] = $value->toArray();
            } else {
                $array[$key] = $value;
            }
        }
        return $array;
    }


    /**
     * Support isset() overloading on PHP 5.1
     *
     * @param string $name
     * @return bool
     */
    public function __isset($name)
    {
        return isset($this->_data[$name]);
    }


    /**
     * Support unset() overloading on PHP 5.1
     *
     * @param  string $name
     * @throws Exception
     * @return void
     */
    public function __unset($name)
    {
        if ($this->_allowModifications) {
            unset($this->_data[$name]);
            $this->_count = count($this->_data);
            $this->_skipNextIteration = true;
        } else {
            throw new InvalidArgumentException('Velis\Config is read only');
        }
    }

    /**
     * {@inheritDoc}
     */
    public function count(): int
    {
        return $this->_count;
    }

    /**
     * {@inheritDoc}
     */
    #[\ReturnTypeWillChange]
    public function current()
    {
        $this->_skipNextIteration = false;

        return current($this->_data);
    }

    /**
     * {@inheritDoc}
     */
    #[\ReturnTypeWillChange]
    public function key()
    {
        return key($this->_data);
    }

    /**
     * {@inheritDoc}
     */
    #[\ReturnTypeWillChange]
    public function next()
    {
        if ($this->_skipNextIteration) {
            $this->_skipNextIteration = false;
            return;
        }
        next($this->_data);
        $this->_index++;
    }

    /**
     * {@inheritDoc}
     */
    public function rewind(): void
    {
        $this->_skipNextIteration = false;
        reset($this->_data);
        $this->_index = 0;
    }

    /**
     * {@inheritDoc}
     */
    public function valid(): bool
    {
        return $this->_index < $this->_count;
    }

    /**
     * {@inheritDoc}
     */
    public function offsetExists($offset): bool
    {
        return $this->__isset($offset);
    }

    /**
     * {@inheritDoc}
     */
    #[\ReturnTypeWillChange]
    public function offsetGet($offset)
    {
        return $this->__get($offset);
    }

    /**
     * {@inheritDoc}
     * @throws Exception
     */
    public function offsetSet($offset, $value): void
    {
        $this->__set($offset, $value);
    }

    /**
     * {@inheritDoc}
     * @throws Exception
     */
    public function offsetUnset($offset): void
    {
        $this->__unset($offset);
    }


    /**
     * Returns the section name(s) loaded.
     *
     * @return mixed
     */
    public function getSectionName()
    {
        if (is_array($this->_loadedSection) && count($this->_loadedSection) == 1) {
            $this->_loadedSection = $this->_loadedSection[0];
        }
        return $this->_loadedSection;
    }


    /**
     * Returns true if all sections were loaded
     *
     * @return bool
     */
    public function areAllSectionsLoaded()
    {
        return $this->_loadedSection === null;
    }


    /**
     * Merge another Velis\Config with this one. The items
     * in $merge will override the same named items in
     * the current config.
     *
     * @param \Velis\Config\Config $merge
     * @return \Velis\Config\Config
     */
    public function merge(Config $merge)
    {
        foreach ($merge as $key => $item) {
            if (array_key_exists($key, $this->_data)) {
                if ($item instanceof Config && $this->$key instanceof Config) {
                    $this->$key = $this->$key->merge(new Config($item->toArray(), !$this->readOnly()));
                } else {
                    $this->$key = $item;
                }
            } elseif ($item instanceof Config) {
                $this->$key = new Config($item->toArray(), !$this->readOnly());
            } else {
                $this->$key = $item;
            }
        }
        return $this;
    }


    /**
     * Prevent any more modifications being made to this instance. Useful
     * after merge() has been used to merge multiple Velis\Config objects
     * into one object which should then not be modified again.
     *
     */
    public function setReadOnly()
    {
        $this->_allowModifications = false;
        foreach ($this->_data as $key => $value) {
            if ($value instanceof Config) {
                $value->setReadOnly();
            }
        }
    }


    /**
     * Returns if this Velis\Config object is read only or not.
     *
     * @return bool
     */
    public function readOnly()
    {
        return !$this->_allowModifications;
    }


    /**
     * Get the current extends
     *
     * @return array
     */
    public function getExtends()
    {
        return $this->_extends;
    }


    /**
     * Set an extend for Velis\Config_Writer
     *
     * @param  string $extendingSection
     * @param  string $extendedSection
     * @return void
     */
    public function setExtend($extendingSection, $extendedSection = null)
    {
        if ($extendedSection === null && isset($this->_extends[$extendingSection])) {
            unset($this->_extends[$extendingSection]);
        } elseif ($extendedSection !== null) {
            $this->_extends[$extendingSection] = $extendedSection;
        }
    }


    /**
     * Throws an exception if $extendingSection may not extend $extendedSection,
     * and tracks the section extension if it is valid.
     *
     * @param  string $extendingSection
     * @param  string $extendedSection
     * @throws Exception
     * @return void
     */
    protected function _assertValidExtend($extendingSection, $extendedSection)
    {
        // detect circular section inheritance
        $extendedSectionCurrent = $extendedSection;
        while (array_key_exists($extendedSectionCurrent, $this->_extends)) {
            if ($this->_extends[$extendedSectionCurrent] == $extendingSection) {
                throw new \RuntimeException('Illegal circular inheritance detected');
            }
            $extendedSectionCurrent = $this->_extends[$extendedSectionCurrent];
        }
        // remember that this section extends another section
        $this->_extends[$extendingSection] = $extendedSection;
    }


    /**
     * Merge two arrays recursively, overwriting keys of the same name
     * in $firstArray with the value in $secondArray.
     *
     * @param  mixed $firstArray  First array
     * @param  mixed $secondArray Second array to merge into first array
     * @return array
     */
    protected function _arrayMergeRecursive($firstArray, $secondArray)
    {
        if (is_array($firstArray) && is_array($secondArray)) {
            return array_replace_recursive($firstArray, $secondArray);
        }
        return $secondArray;
    }


    /**
     * Set internal error handler
     *
     * @return void
     */
    protected function _setErrorHandler()
    {
        set_error_handler(array($this, '_handleError'));
    }


    /**
     * Restore internal error handler
     *
     * @return array Handled error messages
     */
    protected function _restoreErrorHandler()
    {
        restore_error_handler();
        $errorMessages = $this->_errorMessages;
        $this->_errorMessages = array();
        return $errorMessages;
    }


    /**
     * Handle internal errors
     *
     * @param int $errno
     * @param string $errstr
     * @param string $errfile
     * @param int $errline
     * @return void
     */
    protected function _handleError($errno, $errstr, $errfile, $errline)
    {
        $this->_errorMessages[] = trim($errstr);
    }
}
