<?php

class Context
{
    private $id;
    protected $label;

    protected function Context($data)
    {
        $this->id = $data["id"];
        $this->label = $data["label"];
    }

    public function getId()
    { return $this->id; }

    public function getLabel()
    { return $this->label; }

    private static $cache = array();
    public static function Load($ids)
    {
        global $account;

        $toLoad = array();
        foreach ($ids as $id)
            if (!isset(self::$cache[$id]))
                array_push($toLoad, $id);
        if (empty($toLoad))
            return;
        foreach ($toLoad as $i)
            self::$cache[$i] = null;
        $data = rawQuery("select * from context where userid=? and id in (" .str_repeat('?,', count($toLoad) - 1) . '?)', array_merge([$account->getId()], $toLoad));
        foreach ($data as $i)
            self::$cache[$i["id"]] = new Context($i);
    }

    public static function LoadAll()
    {
        global $account;

        $toNotLoad = array();
        if (count(self::$cache))
            $data = rawQuery("select * from context where userid=? and id not in (" .str_repeat('?,', count(self::$cache) - 1) . '?)', array_merge([$account->getId()], array_keys(self::$cache)));
        else
            $data = rawQuery("select * from context where userid=?", [$account->getId()]);
        foreach ($data as $i)
            self::$cache[$i["id"]] = new Context($i);
    }

    public static function ListAll(): Array
    {
        $result = [];
        foreach (self::$cache as $id => $e)
            array_push($result, $e);
        return $result;
    }

    public static function Get($id)
    {
        if (isset(self::$cache[$id]))
            return self::$cache[$id];
        self::Load([$id]);
        return self::$cache[$id];
    }

    public static function Serialize($ctxs) {
        $contexts = "";
        foreach ($ctxs as $i)
            $contexts = $contexts .',' .$i->getId();
        $contexts = $contexts .',';
        return $contexts;
    }

}

