1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
use std::fs::File;
use std::path::*;
use std::io::Read;
use std::fs;
#[cfg(feature="serde_support")]
use serde_json::*;

use ndata::data::*;
use ndata::dataobject::*;
use ndata::dataarray::*;
use ndata::databytes::*;

use crate::rand::*;

static mut STORE_PATH:Option<PathBuf> = None;

#[derive(Debug)]
pub struct DataStore {
  pub root: PathBuf,
}

impl DataStore {
  pub fn init(dir:&str) -> (&str, (((usize,usize),(usize,usize)),((usize,usize),(usize,usize)),((usize,usize),(usize,usize)))) {
    let d = Path::new(dir);
    unsafe { STORE_PATH = Some(d.to_path_buf()); }
    
    Rand::init();
    let q = ndata::init();
    
    let o = DataObject::new();
    let _x = o.incr();
    (dir, q)
  }
  
  #[allow(dead_code)]
  pub fn mirror(q:(&str, (((usize,usize),(usize,usize)),((usize,usize),(usize,usize)),((usize,usize),(usize,usize))))) {
    let d = Path::new(q.0);
    unsafe { STORE_PATH = Some(d.to_path_buf()); }
    
    Rand::init();
    ndata::mirror(q.1);
    
    let o = DataObject::new();
    let _x = o.incr();
  }
  
  pub fn new() -> DataStore {
    let path;
    unsafe {
      path = STORE_PATH.as_ref().unwrap();
    }
    return DataStore {
      root: path.to_path_buf(),
    };
  }
  
  #[allow(dead_code)]
  pub fn globals() -> DataObject {
    DataObject::get(0)
  }
  
  #[allow(dead_code)]
  pub fn gc() {
    DataObject::gc();
    DataArray::gc();
    DataBytes::gc();
  }
  
  pub fn lookup_cmd_id(&self, lib:&str, ctl:&str, cmd:&str) -> String {
    let data = self.get_data(lib, "controls");
    let data = data.get_object("data").get_array("list");
    for c in data.objects() {
      let c = c.object();
      let n = c.get_string("name");
      if n == ctl {
        let ctlid = c.get_string("id");
        let ctldata = self.get_data(lib, &ctlid);
        let ctldata = ctldata.get_object("data");
        for cmddata in ctldata.get_array("cmd").objects() {
          let cmddata = cmddata.object();
          let n2 = cmddata.get_string("name");
          if n2 == cmd {
            return cmddata.get_string("id");
          }
        }
      }
    }
    panic!("No such command {}:{}:{}", lib, ctl, cmd);
  }
  
  #[allow(dead_code)]
  pub fn set_data(&self, db: &str, id: &str, data:DataObject) {
    let mut d = data.get_object("data");
    if d.has("attachmentkeynames") {
      let v = d.get_array("attachmentkeynames");
      for b in v.objects() {
        let b = &b.string();
        let aid = id.to_string()+"."+b;
        let f = self.get_data_file(db, &aid);
        let s = Data::as_string(d.get_property(b));
        fs::create_dir_all(f.parent().unwrap()).unwrap();
        fs::write(f, s).expect("Unable to write file");
        d.remove_property(b);
      }
    }
  
    let s = data.to_string();
    let f = self.get_data_file(db, id);
    fs::create_dir_all(f.parent().unwrap()).unwrap();
    fs::write(f, s).expect("Unable to write file");
  }
  
  #[cfg(feature="serde_support")]
  pub fn get_json(&self, db: &str, id: &str) -> Value {
    let path = self.get_data_file(db, id);
    let s = self.read_file(path);
    let mut data: Value = serde_json::from_str(&s).unwrap();
    let attachments: Value = data["data"]["attachmentkeynames"].to_owned();
    if attachments.is_array() {
      for a in attachments.as_array().unwrap().into_iter(){
        let b = &a.as_str().unwrap();
        let aid = id.to_string()+"."+b;
        let apath = self.get_data_file(db, &aid);
        if apath.exists(){
          let astr = self.read_file(apath);
          if astr.len() > 0 && astr[0..1].to_string() == "{" { // FIXME - Legacy hack
            data["data"][b] = serde_json::from_str(&astr).unwrap(); 
          } else {
            data["data"][b] = serde_json::Value::String(astr); 
          }
        }
      }
    }
    data
  }
  
  pub fn get_data(&self, db: &str, id: &str) -> DataObject {
    #[cfg(feature="serde_support")]
    {
      let data = self.get_json(db, id);
      return DataObject::from_json(data);
    }
    #[allow(unreachable_code)]
    {
      let path = self.get_data_file(db, id);
      let s = self.read_file(path);
      let data = DataObject::from_string(&s);
      let mut d = data.get_object("data");
      if d.has("attachmentkeynames") {
        let attachments: DataArray = d.get_array("attachmentkeynames");
        for a in attachments.objects(){
          let b = &a.string();
          let aid = id.to_string()+"."+b;
          let apath = self.get_data_file(db, &aid);
          let astr = self.read_file(apath);
          if astr.len() > 0 && astr[0..1].to_string() == "{" { // FIXME - Legacy hack
            d.put_object(b, DataObject::from_string(&astr)); 
          } else {
            d.put_str(b, &astr); 
          }
        }
      }
      return data;
    }
  }
  
  pub fn exists(&self, db: &str, id: &str) -> bool {
    self.get_data_file(db, id).exists()
  }
  
  pub fn get_data_file(&self, db: &str, id: &str) -> PathBuf {
    let mut path = self.root.join(db);
    path = self.get_sub_dir(path, id, 4, 4);
    path.push(id);
    path
  }
  
  fn get_sub_dir(&self, mut path: PathBuf, id: &str, chars: usize, levels: usize) -> PathBuf {
    let l:usize = chars * levels;
    let mut s = id.to_string();
    while s.len()<l {
      s = s + "_";
    }
    let mut i = 0;
    while i<levels{
      let n:usize = i * chars;
      let m:usize = n + chars;
      i = i + 1;
      let sub = &s[n..m];
      path.push(sub);
    }
    path
  }
  
  pub fn read_file(&self, path: PathBuf) -> String {
    if !path.exists() { println!("Missing file {:?}", path); }
    let mut f = File::open(path).unwrap();
    let mut s = String::new();
    f.read_to_string(&mut s).unwrap();
    s
  }
}