<?php
    class dirDB{
        private $path;

        function __construct($path) {
            $this->path=$path;
        }

        public function get($table,$id){
            $base=$this->path;
            return $this->read("$base/$table/$id.json");
        }

        public function list($table,$filter=false){
            $base=$this->path;
            $result=[];
            foreach (glob("$base/$table/*.json") as $file) {
                $result[]=$this->read($file);
            }
            return $result;
        }

        public function insert($table,$data,$many=false){
            $url=$this->url;
            if ($many){
                foreach($data as $v){
                    $id=$v["id"]=$this->guidv4();
                    $this->write("$base/$table/$id.json",$v);
                }
            }else{
                $id=$data["id"]=$this->guidv4();
                $this->write("$base/$table/$id.json",$data);
            }
        }

        public function update($table,$changes){
            $this->call("${url}/action/updateOne",[
                "dataSource"=>$this->dataSource,
                "database"=>$this->db,
                "collection"=>$table,
                "filter"=>[ "_id"=>$id ],
                "update"=>[ "$set"=>$changes ],
            ]);
        }

        public function replace($table,$data){
            $this->call("${url}/action/replaceOne",[
                "dataSource"=>$this->dataSource,
                "database"=>$this->db,
                "collection"=>$table,
                "filter"=>[ "_id"=>$id ],
                "replacement"=>$data,
            ]);
        }

        public function delete($table,$id){
            $this->call("${url}/action/deleteOne",[
                "dataSource"=>$this->dataSource,
                "database"=>$this->db,
                "collection"=>$table,
                "filter"=>[ "_id"=>$id ],
            ]);
        }

        function read($path){
            if (!file_exists($path))
                return null;
            $result=file_get_contents($path);
            if ($result===false)
                return null;
            return json_decode($result,true);
        }

        function write($path,$data){
            var_dump($path);die();            
            $data=json_encode($data);
            file_put_contents($path,$data);
        }

        function guidv4($data = null) {
            // Generate 16 bytes (128 bits) of random data or use the data passed into the function.
            $data = $data ?? random_bytes(16);
            assert(strlen($data) == 16);
        
            // Set version to 0100
            $data[6] = chr(ord($data[6]) & 0x0f | 0x40);
            // Set bits 6-7 to 10
            $data[8] = chr(ord($data[8]) & 0x3f | 0x80);
        
            // Output the 36 character UUID.
            return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
        }        
    }

?>