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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
use crate::datatypes::RandomData;
use crate::generation::OutputType;
use crate::specification::{DataType as DT, Model, Specification};

use std::borrow::Borrow;
use std::collections::HashMap;
use std::path::PathBuf;
use std::rc::Rc;
use std::str::FromStr;

// ------- TODO: Check these -------
use std::convert::AsRef;
use std::fs::{create_dir_all, read_to_string, File};
use std::iter::FromIterator;

use csv::Writer as Csv;
use serde_json::{from_str, to_string};
use std::io::Write;

// ---------------------------------

pub type ModelDataMap = HashMap<String, Vec<HashMap<String, String>>>;

fn get_model_children(model: &Model) -> Vec<String> {
	model
		.type_iter()
		.filter_map(|(key, data_type)| {
			if let DT::Model(def) = data_type {
				Some(def.clone())
			} else if let DT::List(nested) = data_type {
				match nested.borrow() {
					DT::Model(def) => Some(def.clone()),
					_ => None,
				}
			} else {
				None
			}
		})
		.collect()
}

type BoolResult = Result<(), String>;
fn validate_dependencies(deps: &Vec<String>, spec: &Specification) -> BoolResult {
	let types_valid: Vec<BoolResult> = deps
		.iter()
		.map(|data_type| {
			if spec.has_model(data_type) {
				Ok(())
			} else {
				Err(format!("No such type {}", data_type))
			}
		})
		.collect();

	for e in types_valid {
		e?;
	}

	Ok(())
}

#[derive(Clone, Debug)]
struct GenData {
	model: Model,
	data: HashMap<String, String>,
}

#[derive(Clone, Debug)]
struct GenContext {
	pub parent_context: Option<Box<GenContext>>,
	pub parent_model: Option<GenData>,
	pub models: ModelDataMap,
}

enum RefType {
	Parent,
}

impl FromStr for RefType {
	type Err = &'static str;

	fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> {
		match s {
			"^" => Ok(RefType::Parent),
			_ => Err("Invalid ref string"),
		}
	}
}

impl GenContext {
	pub fn add_model_data(&mut self, data_type: String, data_values: HashMap<String, String>) {
		let list = self.models.entry(data_type).or_insert(Vec::new());
		list.push(data_values);
	}
	pub fn merge_model_data(&mut self, other_data: &mut ModelDataMap) {
		other_data.iter_mut().for_each(|(data_type, values)| {
			let list = self.models.entry(data_type.clone()).or_insert(Vec::new());
			list.append(values);
		});
	}
	pub fn fetch_ref_path(&self, parts: Vec<String>) -> Option<HashMap<String, String>> {
		if parts.len() == 0 {
			None
		} else if parts.len() == 1 {
			let final_ref = parts.get(0).unwrap();
			match RefType::from_str(final_ref).ok()? {
				RefType::Parent => {
					if let Some(parent_model) = &self.parent_model {
						Some(parent_model.data.clone())
					} else {
						None
					}
				}
				_ => None,
			}
		} else {
			let next_ref = parts.get(0).unwrap();
			let rest: Vec<String> = parts.iter().skip(1).map(|s| s.clone()).collect();

			match RefType::from_str(next_ref).ok()? {
				RefType::Parent => {
					if let Some(parent_ctx) = &self.parent_context {
						let parent: &GenContext = parent_ctx.borrow();
						parent.fetch_ref_path(rest)
					} else {
						None
					}
				}
				_ => None,
			}
		}
	}
}

pub fn from_spec(
	model_name: String,
	spec: Specification,
	quantity: usize,
) -> Result<ModelDataMap, String> {
	let initial_model = spec.get_definition(&model_name);
	let deps = get_model_children(initial_model);

	validate_dependencies(&deps, &spec)?;

	let mut initial_context = GenContext {
		parent_context: None,
		parent_model: None,
		models: HashMap::new(),
	};

	for _ in 0..quantity {
		generate_model_data(
			model_name.clone(),
			initial_model,
			&mut initial_context,
			&spec,
		);
	}

	Ok(initial_context.models)
}

fn generate_model_data(
	model_type: String,
	model: &Model,
	ctx: &mut GenContext,
	spec: &Specification,
) {
	let mut model_data: HashMap<String, String> = HashMap::new();
	let mut child_models: Vec<(String, DT)> = Vec::new();

	model
		.type_iter()
		.for_each(|(property, data_type)| match data_type {
			DT::RandomData(random_data) => {
				let data = random_data.to_string();
				&model_data.insert(property.clone(), data);
			}
			DT::Model(_) => {
				child_models.push((property.clone(), data_type.clone()));
			}
			DT::List(_) => {
				child_models.push((property.clone(), data_type.clone()));
			}
			DT::Reference {
				ref path,
				property: ref_prop,
			} => {
				let parts = path.split("~").map(String::from).collect();
				let ref_model_data = ctx.fetch_ref_path(parts);
				match ref_model_data {
					Some(data_set) => {
						let data = data_set.get(ref_prop).unwrap();
						&model_data.insert(property.clone(), data.clone());
					}
					None => {}
				}
			}
			_ => {}
		});

	ctx.add_model_data(model_type, model_data.clone());

	child_models.iter().for_each(|(property, model_type)| {
		let (gen_name, iterations) = if let DT::List(nested) = model_type {
			match nested.borrow() {
				DT::Model(next_model_name) => (next_model_name.clone(), 5),
				_ => return,
			}
		} else if let DT::Model(next_model_name) = model_type {
			(next_model_name.clone(), 1)
		} else {
			return;
		};

		for _ in 0..iterations {
			let mut next_model_ctx = GenContext {
				parent_context: Some(Box::new(ctx.clone())),
				parent_model: Some(GenData {
					model: model.clone(),
					data: model_data.clone(),
				}),
				models: HashMap::new(),
			};
			generate_model_data(
				gen_name.clone(),
				&spec.get_definition(&gen_name),
				&mut next_model_ctx,
				&spec,
			);
			ctx.merge_model_data(&mut next_model_ctx.models);
		}
	});
}

pub fn write_output(
	folder: &PathBuf,
	data: ModelDataMap,
	spec: Specification,
	out_type: OutputType,
	pretty: bool,
) {
	create_dir_all(&folder);
	match out_type {
		OutputType::CSV => data.iter().for_each(|(type_name, model_list)| {
			let mut path = PathBuf::from(&folder);
			path.push(&type_name);
			path = path.with_extension(out_type.as_extension());

			let mut file = File::create(path).unwrap();
			let ordering = spec.get_serialize_ref(&type_name);
			let mut writer = Csv::from_writer(file);
			for data_set in model_list {
				let mut row: Vec<String> = Vec::new();
				if let Some(order) = ordering {
					for key in order.iter() {
						row.push(
							data_set
								.get(key)
								.unwrap_or(&String::from("null"))
								.to_string(),
						);
					}
				} else {
					data_set.values().for_each(|v| row.push(v.clone()));
				}
				writer.write_record(&row).unwrap();
			}
		}),
		OutputType::JSON => {
			data.iter().for_each(|(type_name, model_list)| {
				let mut path = PathBuf::from(&folder);
				path.push(&type_name);
				path = path.with_extension(out_type.as_extension());
				let mut file = File::create(path).expect("Creating file");

				let contents = if pretty {
					serde_json::to_vec_pretty(model_list).expect("Serialising formatted models")
				} else {
					serde_json::to_vec(model_list).expect("Serialising models")
				};

				file.write_all(contents.as_slice())
					.expect("Write model data to file");
				file.flush().expect("Flush file contents");
			});
		}
	}
}