<?php

namespace Velis\Lang;

use Velis\Model\DataObject;
use Velis\Lang;

/**
 * Lang key model
 *
 * @author Michał Ćwikliński <emce@velis.pl>
 * @author Olek Procki <olo@velis.pl>
 */
class Key extends DataObject
{
    /**
     * Default order phrase
     * @var string
     */
    protected static $_listDefaultOrder = 'lang_key_id';


    /**
     * Returns related sql table
     * @return string
     */
    protected function _getTableName()
    {
        return 'app.lang_key_tab';
    }


    /**
     * Return array of primary keys
     * @return array
     */
    protected function _getPrimaryKeyField()
    {
        return array('lang_group_id','lang_key_id');
    }


    /**
     * Returns key name
     * @return string
     */
    public function getName()
    {
        return $this['lang_key'];
    }


    /**
     * Remove key
     * @return bool
     */
    public static function remove($filter)
    {
        self::$_db->startTrans();

        $params = array(
                        'lang_key_id' => $filter['lang_key_id'],
                        'lang_group_id' => $filter['lang_group_id'],
                );
        self::$_db->execDML("DELETE FROM app.lang_value_tab WHERE lang_key_id = :lang_key_id AND lang_group_id = :lang_group_id", $params);
        self::$_db->execDML("DELETE FROM app.lang_key_tab WHERE lang_key_id = :lang_key_id AND lang_group_id = :lang_group_id", $params);

        self::$_db->commit();

        return true;
    }


    /**
     * Returns group data
     *
     * @param string $group
     * @return array
     */
    public static function byGroup($group)
    {
        return self::listAll(array("lang_group_id" => $group));
    }


    /**
     * Checks if group exists
     *
     * @param string $group
     * @return int
     */
    public static function groupExists($group)
    {
        return self::$_db->getOne(
            "SELECT COUNT(*) FROM app.lang_group_tab WHERE lang_group_id=:group",
            array ("group" => $group)
        );
    }


    /**
     * Checks if constant exists
     *
     * @param string $const
     * @param string $group
     *
     * @return int
     */
    public static function constantExists($const, $group)
    {
        return self::$_db->getOne(
            "SELECT COUNT(*) FROM app.lang_key_tab WHERE lang_key=:value AND lang_group=:group",
            array (
                "value"    => $const,
                "group"    => $group
            )
        );
    }


    public function save($updateObjectId = false)
    {
        try {
            return parent::save($updateObjectId);
        } catch (\Exception $e) {
            if ($e->getCode() == 55000) {
                $this->_setId(self::$_db->getOne(
                    'SELECT lang_key_id FROM app.lang_key_tab WHERE lang_group=:lang_group AND lang_key=:lang_key',
                    array (
                        'lang_group' => $this->lang_group,
                        'lang_key'   => $this->lang_key
                    )
                ));
                return $this;
            }
        }
    }


    /**
     * Adds new group
     *
     * @param string $group
     *
     * @return bool
     *
     * @throws \LogicException
     */
    public static function createGroup($group)
    {
        if (self::groupExists(strtoupper($group))) {
            throw new \LogicException(Lang::get('LANG_GROUP_EXISTS'));
        }

        try {
            self::$_db->insert('app.lang_group_tab', array('lang_group_id' => $group));
        } catch (Exception $e) {
            throw $e;
        }

        return true;
    }


    /**
     * Renema lang_key_id
     * @param array $filter
     */
    public static function renameKey($filter)
    {
        $params = array (
                'lang_group_id' => $filter['lang_group_id'],
                'lang_key_id' => $filter['new_lang_key_id'],
        );

        $key = new Key($params);
        $key->add();

        try {
            $params = array (
                    'lang_group_id' => $filter['lang_group_id'],
                    'lang_key_id' => $filter['lang_key_id'],
                    'new_lang_key_id' => $filter['new_lang_key_id'],
            );

            self::$_db->startTrans();

            $sql = 'INSERT INTO app.lang_value_tab
                    SELECT lang_group_id, :new_lang_key_id, lang_id, value FROM app.lang_value_tab WHERE lang_group_id=:lang_group_id AND lang_key_id=:lang_key_id';
            self::$_db->execDML($sql, $params);

            unset($params['new_lang_key_id']);

            $sql = 'DELETE FROM app.lang_value_tab WHERE lang_group_id=:lang_group_id AND lang_key_id=:lang_key_id';
            self::$_db->execDML($sql, $params);

            $sql = 'DELETE FROM app.lang_key_tab WHERE lang_group_id=:lang_group_id AND lang_key_id=:lang_key_id';
            self::$_db->execDML($sql, $params);

            self::$_db->commit();

            echo $filter['new_lang_key_id'];
        } catch (Exception $e) {
            self::$_db->rollback();
            echo $e->getMessage();
        }
    }
}
