<?php
class ModuleSetting extends MY_Model
{
	const DB_TABLE = 'module_settings';
    const DB_TABLE_PK = 'module_setting_id';

    private static $cache = array();

    /**
     * Load a module by key.
     * Rather than have 2 queries for each setting we need to look up (which could amount to lots) we're going to cache all settings by instance ID.
     *
     * @param [type] $module_instance_id [description]
     * @param [type] $key                [description]
     */
	function LoadByModuleKey($module_instance_id, $key)
	{
		//If we've already cached this module instance, lookup the key and load it.
		if(isset(self::$cache["$module_instance_id"]["$key"]))
		{
			return $this->populate(self::$cache["$module_instance_id"]["$key"]);
		}

		//Grab all settings for this module instance and cache them. We'll grab the specific key we want afterwards.
	  	$query = $this->db->query("SELECT * FROM module_settings WHERE module_instance_id=?", array($module_instance_id));

		foreach($query->result() as $row)
		{
			self::$cache["$module_instance_id"][$row->key] = $row;
		}

		//If a module setting has not yet been defined, it will generate warnings because the key has not been cached.
		//For extra safety, we double check that the key has been defined in our cache.
		if(isset(self::$cache["$module_instance_id"]["$key"]))
		{
			return $this->populate(self::$cache["$module_instance_id"]["$key"]);
		}
		else
		{
			return false;
		}
	}

	function load_by_instance_id($id)
	{
		$key = "module:settings:" . $id;

		if(($results = $this->cache->get($key)) === false)
		{
			$query = $this->db->query("SELECT s.*
			                          FROM module_settings AS s
			                          INNER JOIN module_instances AS i ON s.module_instance_id=i.module_instance_id
			                          WHERE i.module_instance_id=?
			                          ORDER BY i.sort, i.tag",
			                          array($id));
			$results = array();

			foreach($query->result() as $row)
			{
				$results[$row->key] = $row;
			}

			$this->cache->save($key, $results, 86400);
		}

		return $results;
	}

    public function delete_all($module_instance_id)
    {
    	$this->db->query("DELETE FROM module_settings WHERE module_instance_id=?",
    	                 array($module_instance_id));
    }

    public function delete_all_others($module_instance_id, $ids)
    {
    	$this->db->query("DELETE FROM module_settings WHERE module_instance_id=? AND module_setting_id NOT IN ($ids)",
    	                 array($module_instance_id));
    }
}
