<?php

namespace Velis;

use Velis\Model\BaseModel;
use Velis\Model\DataObject;

/**
 * Dictionary model
 * @author Olek Procki <olo@velis.pl>
 */
class Dictionary extends BaseModel
{
    /**
     * Buffered dictionaries
     * @var array
     */
    protected static $_buffer = [];

    /**
     * Returns cached dictionary
     * @param string $dictTable
     * @param bool $full
     * @param string $key
     * @param string $name
     * @return array
     */
    public static function get($dictTable, $full = false, $key = null, $name = null)
    {
        $cacheName = str_replace(['.', '_tab'], ['_', '_dict'], $dictTable);

        if ($key == null) {
            $key = DataObject::primaryKeyName($dictTable);
        }

        if (!isset(self::$_buffer[$cacheName])) {
            self::$_buffer[$cacheName] = App::$cache[$cacheName];

            // check if cache expired
            if (self::$_buffer[$cacheName] === null) {
                self::$_buffer[$cacheName] = [];
                foreach (self::$_db->fetchTable($dictTable) as $row) {
                    self::_parseCompositeFields($dictTable, $row);
                    self::$_buffer[$cacheName][$row[$key]] = $row;
                }
                App::$cache[$cacheName] = self::$_buffer[$cacheName];
            }
        }

        if (!$full) {
            $entries = [];
            foreach (self::$_buffer[$cacheName] as $key => $row) {
                $entry = new DictionaryEntry(self::$_buffer[$cacheName][$key]);
                $entries[$key] = $entry->getName();
            }

            return $entries;
        } else {
            return self::$_buffer[$cacheName];
        }
    }

    /**
     * Decompose composite type into separated columns
     * @param string $dictTable
     * @param array $data
     */
    protected static function _parseCompositeFields($dictTable, &$data)
    {
        $columns = self::$_db->getColumns($dictTable);
        foreach ($data as $field => $value) {
            if (is_array($columns[$field]['type_fields'])) {
                $fields = [];
                foreach ($columns[$field]['type_fields'] as $typeField) {
                    $fields[] = $field . '_' . $typeField;
                }

                $data = array_merge($data, self::$_db->recordToArray($data[$field], $fields));
            }
        }
    }
}
