<?php

namespace Velis;

use Velis\Model\Cacheable;
use Velis\Model\DataObject;
use Velis\Model\DataObject\NoColumnsException;

/**
 * Timezone model
 * @author Damian Kurek <damian.kurek@velis.pl>
 */
class Timezone extends DataObject implements Cacheable
{
    protected static $_listDefaultOrder = 'timezone_id';

    /**
     * Returns table name
     *
     * @return string
     */
    protected function _getTableName()
    {
        return 'app.timezone_tab';
    }


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


    /**
     * Returns default timezone
     *
     * @throws NoColumnsException
     */
    public static function getDefaultTimezone(): Timezone
    {
        $instance = new self();
        $timezone = null;

        // this condition should prevent connection infinite loop (expired/empty cache scenario)
        if (self::$_db?->isConnected() || App::$cache->has($instance->_getListCacheName())) {
            $timezone = Arrays::find(self::listCached(), 'is_default', 1);
        }

        if (!$timezone) {
            $defaultTimezoneName = App::$config->settings->defaultTimezoneName ?? 'Europe/Warsaw';

            // Creating a new empty timezone object and then appending data is done to prevent
            // invoking method parseCompositeFields() as it causes infinite loop occuring
            // when multipleTimezoneSupport setting is enabled and localhost is connected to prod db via tunnel
            $timezone = new self();
            $timezone->append(['timezone_id' => $defaultTimezoneName, 'is_default' => 1]);
        }

        return $timezone;
    }


    /**
     * Updates timezone
     *
     * @param bool $checkDiff
     * @return $this
     * @throws \Exception
     */
    public function modify($checkDiff = false)
    {
        if ($this['is_default']) {
            self::$_db->execDML('UPDATE app.timezone_tab SET is_default=0');
        }
        parent::modify($checkDiff);

        return $this;
    }


    /**
     * Removes timezone
     *
     * @return bool
     */
    public function remove()
    {
        return parent::_remove();
    }


    /**
     * {@inheritDoc}
     */
    public static function listForCache()
    {
        $instance = new static();
        $query = "SELECT * FROM " . $instance->_getTableName();
        $result = [];
        foreach (self::$_db->getAll($query) as $row) {
            $result[$row['timezone_id']] = new static($row);
        }

        return $result;
    }


    /**
     * Sets database timezone
     */
    public static function setTimezone()
    {
        if (App::$config->hasTimezoneSupport() && App::$user->getTimezone()) {
            self::$_db->execDML("SET timezone TO '" . App::$user->getTimezone() . "'");
        }
    }
}
