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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
//! # Contack vCard
//!
//! Contack is a simple library for managing contacts in rust.
//! Contack-vCard allows simple exporting to the vcard format.
//! Here is an example
//! ```
//! fn main() {
//! 	// Creates a Contact
//! 	let mut contact = contack::Contact::new (
//!			contack::name::Name {
//!				given : 		Some("John"),
//!				additional : 	None,
//!				family :		Some("Toohey"),
//!				prefixes : 		None,
//!				suffixes :		None,
//!			}
//! 	);
//! 	// Sets the email
//! 	contact.contact_information.push (
//!			contack::contact_information::ContactInformation::new (
//!				"john_t@mailo.com",
//!				Email
//!			)
//! 	);
//! 	// Turns it to a vCard
//! 	let vcontact = contack_vcard::contack_to_vcard (
//!			contact
//! 	);
//! 	// Prints it out
//! 	println!("{}", vcontact);
//!	}
//!	```
//!

pub mod error;
pub extern crate vcard;

use error::image::VCardImageValueError;
use std::error::Error;
use std::collections::HashSet;

use vcard::{Set, VCard, XPropertyName};
use vcard::properties::*;
use vcard::values::text::{Text, Component};
use vcard::values::name_value::NameValue;
use vcard::values::image_value::ImageValue;
use vcard::values::date_time::{DateAndOrTime, Date};
use vcard::values::address_value::AddressValue;
use vcard::values::type_value::{TypeValue, TypeValueWithTelephoneType};
use vcard::values::email_value::EmailValue;

use vcard::parameters::property_id::PropertyID;
use vcard::values::property_id_value::PropertyIDValue;

use vcard::parameters::typ::{Type, TypeWithTelType};

use vcard::values::preference_value::PreferenceValue;
use vcard::parameters::preference::Preference;

use contack::Contact;
use contack::contact_platform::ContactPlatform;

use vcard::parameters::geo::Geo;
use vcard::values::geo_value::Longitude;
use vcard::values::geo_value::Latitude;
use vcard::values::geo_value::GeoValue;

use log::error;

use vcard::values::date_time::Time;
use vcard::values::uid_value::UIDValue;
use vcard::properties::UID;

/// Converts a Contack Contact to a VCard, which can later be written to a file.
#[allow(dead_code)]
pub fn contack_to_vcard(
	contact : &Contact
) -> Result<vcard::VCard, Box<dyn Error>> {

	// Our VCard 
	let mut vcontact = VCard::from_formatted_name (

		// Creates a formatted name
		FormattedName::from_text (
			Text::from_string (

				// Uses the name in the contack to generate a vcard name
				contact.name.to_string()
			)?
		)
	)?;
	/*
	 * Sets the identification properties
	 */

	///////// Sets the unformatted names
	vcontact.names = vset (
		Name::from_name_value(
			NameValue::from_components (
				op_string_to_comp (contact.name.family.as_ref()),
				op_string_to_comp (contact.name.given.as_ref()),
				op_string_to_comp (contact.name.additional.as_ref()),
				op_string_to_comp (contact.name.prefixes.as_ref()),
				op_string_to_comp (contact.name.suffixes.as_ref()),
			)
		)
	)?;

	//////// Sets the nickname
	// Checks if the nickname exists
	if contact.nickname != None {
		// Creates an option
		vcontact.nicknames = vset (
			// Creates it from a text list
			NickName::from_text_list ({
				let mut hash_set = HashSet::new();
				hash_set.insert(
					// Creates the text from string
					Text::from_str(
						&contact.nickname.as_ref().unwrap()
					)?,
				);
				Set::from_hash_set(hash_set)?
			})
		)?;
	}

	//////// Sets the anniversary
	if contact.anniversary != None {
		match {
			contack_time_to_vcard_time (
				contact.anniversary.as_ref().unwrap() // This is safe
			)
		} {
			Some (date) => {
				vcontact.anniversaries = vset(
					Anniversary::from_date_and_or_time (
						DateAndOrTime::DateTime (
							date
						)
					)
				)?;
			},
			_ => {}
		}
	}

	//////// Sets the Bday
	if contact.bday != None {
		match {
			contack_time_to_vcard_time (
				contact.bday.as_ref().unwrap() // This is safe
			)
		} {
			Some(date) => {
				vcontact.birthdays =
					vset (
					Birthday::from_date_and_or_time (
						DateAndOrTime::DateTime (
							date
						)
					)
				)?;
			},
			_ => {}
		}
	}

	//////// Sets the Photo
	if contact.photo != None {
		vcontact.photos = vset (

			// Creates a photo
			Photo::from_image_value (
				// Creates the image value
				contack_uri_to_photo(
					contact.photo.as_ref().unwrap()
				)?
			)
		)?;
	}

	/*
	 * Organisational Properties
	 */

	//////// Sets the title
	if contact.title != None {
		vcontact.titles = vset(
			// Creates a title from text
			Title::from_text (
				
				// Creates a Text from string
				Text::from_string (

					// This is safe (hopefully)
					contact.title.as_ref().unwrap().to_string()
				)?
			)
		)?;
	}

	//////// Sets the role
	if contact.role != None {
		vcontact.roles = vset(
			// Creates a role from text
			Role::from_text (
				
				// Creates a Text from string
				Text::from_string (

					// This is safe (hopefully)
					contact.role.as_ref().unwrap().to_string()
				)?
			)
		)?;
	}

	///////// Sets the Org
	if contact.org != None {
		vcontact.organizations = vset(
			Organization::from_component_list ({
				// Creates a has set to house the org components
				let mut hash_set = HashSet::new();

				// Gets the contact's org
				let org = contact.org.as_ref().unwrap();
				
				/*
                 *  Adds the values to the hashset
                 */
				// Org
				hash_set.insert (
					op_string_to_comp(
						Some(&org.org)
					).unwrap() // This is safe
				);

				// Unit
				hash_set.insert (
					op_string_to_comp(
						Some(&org.unit)
					).unwrap() // This is safe
				);
				
				// Office
				hash_set.insert (
					op_string_to_comp(
						Some(&org.office)
					).unwrap() // This is safe
				);

				// Returns a set
				Set::from_hash_set(hash_set)?
			})
		)?;
	}

	//////// Sets the Logo
	if contact.logo != None {
		vcontact.logos = vset(
			// Creates a logo
			Logo::from_image_value (
				// Creates the image value
				contack_uri_to_photo(
					contact.logo.as_ref().unwrap()
				)?
			)
		)?
	}

	//////// Sets the Contact Information
	{
		// First set up the hash_sets.
		let mut email_set = HashSet::<Email>::new(); // Email
		let mut tel_set = HashSet::<Telephone>::new(); // Telephone
		let mut x_set = HashSet::<XProperty>::new(); // Everything Else

		// Now Loop through
		for ci in &contact.contact_information {
			match ci.platform {
				// Email
				ContactPlatform::Email => {
					email_set.insert ({
						// Creates an Email
						let mut email = Email::from_email_value (
							EmailValue::from_str (
								&ci.value
							)?
						);
						// Sets the Preference
						email.preference = Some(
							preference_from_int(ci.pref)?
						);

						// Sets the type
						if ci.typ != None {
							// Sets the type
							email.typ = Some(
								contack_type_to_vcard_type (
									ci.typ.as_ref().unwrap() // Safety
								)?
							);
						}

						// Sets the PID

						email.property_id = property_id_from_string (
							&ci.pid
						)?;

						email
					});
				},

				// Telephone
				ContactPlatform::Tel => {
					tel_set.insert ({
						// Creates a Telephone
						let mut tel = Telephone::from_text (
							Text::from_str (
								&ci.value
							)?
						);
						if let Telephone::TelephoneValue {
							ref mut typ,
							ref mut preference,
							ref mut property_id,
							..
						} = tel  {
								// Sets the Preference
								*preference = Some(
									preference_from_int(ci.pref)?
								);

								// Sets the type
								if ci.typ != None {
									// Sets the type
									*typ = Some(
										contack_type_to_vcard_tel_type (
											ci.typ.as_ref().unwrap() // Safety
										)?
									);
								}

								// Sets the PID

								*property_id = property_id_from_string (
									&ci.pid,
								)?;
							}
						tel
					});
				},

				// XProps
				_ => {
					x_set.insert ({
						// Creates an XProperty
						let mut v_ci = XProperty::from_text (
							XPropertyName::from_string(
								ci.platform.to_string()
							)?,
							Text::from_str (
								&ci.value
							)?
						);
						// Sets the Preference
						v_ci.preference = Some(
							preference_from_int(ci.pref)?
						);

						// Sets the type
						if ci.typ != None {
							// Sets the type
							v_ci.typ = Some(
								contack_type_to_vcard_type (
									ci.typ.as_ref().unwrap() // Safety
								)?
							);
						}

						// Sets the PID

						v_ci.property_id = property_id_from_string (
							&ci.pid,
						)?;

						v_ci
					});
				},
			}
		}
	}

	/*
     * Delivery Addressing Properties
     */
	vcontact.addresses = Some({
		// Creates the hash set
		let mut hash_set = HashSet::new();

		//// Adds addresses to the hash set
		
		// Work
		if contact.work_address != None {
			hash_set.insert (
				contack_address_to_vcard_address (
					contact.work_address.as_ref().unwrap()
				)?
			);
		};
		// Home
		if contact.home_address != None {
			hash_set.insert (
				contack_address_to_vcard_address (
					contact.home_address.as_ref().unwrap()
				)?
			);
		};

		// Returns the hash set as a set
		Set::from_hash_set(hash_set)?
	});

	/*
     * Explanator Properties
     */
    //////// Sets the UID
    vcontact.uid = Some(
		UID::from_uid_value (
			UIDValue::Text (
				Text::from_str (
					&contact.uid
				)?
			)
		)
    );
	
	Ok(vcontact)
}

// Converts a string to a component
fn op_string_to_comp (
	string : Option<&String>
) -> Option<Component> {
	// Checks if the string is none
	match string {
		// If so we can just return none
		None => None,
		
		// Otherwise we try and convert it
		Some(string) => {

			// We try and make a component
			match Component::from_str(&string) {

				// If it works it works
				Ok(comp) => Some(comp),

				// Otherwise we just log an error and return none.
				// Probably not great practice 😕.
				Err(e) => {
					error!("{}", e);
					None
				},
			}
		}
	}
}

fn contack_time_to_vcard_time(
	date_time : &contack::date_time::DateTime
) -> Option<vcard::values::date_time::DateTime> {
	// Creates a DateTime
	Some (
		vcard::values::date_time::DateTime::from_date_and_time (
			match 
				// Creates a date
				Date::from_year_month_day (
					date_time.year as u16,
					date_time.month,
					date_time.day,
				)
			 {
				Ok(date) => date,
				Err(e) => {
					error!("{:?}", e);
					return None;
				}
			},
			match 
				Time::from_hour_minute_second (
					date_time.hour,
					date_time.minute,
					date_time.second
				)
			 {
				Ok(time) => time,
				Err(e) => {
					error!("{:?}", e);
					return None;
				},
			}
		)
	)
}

fn contack_uri_to_photo (
	uri : &contack::uri::Uri
) -> Result<ImageValue, Box<dyn Error>> {
	match uri {
		
		// Creates a Bytes
		contack::uri::Uri::Bytes{val, mime} => {
			match {
				// Parses some Base64
				ImageValue::from_base64 (

					// Gets the mime
					mime.as_str().parse::<vcard::Mime>()?,

					// Gets the bytes
					vcard::validators::base64::Base64::from_string (
						base64::encode(val),
					)?
				)
			} {
				// Good
				Ok(image_value)	=> Ok(image_value),
				// Throws an Error
				Err(image_value_error)	=> {
					return Err(
						Box::new(
							VCardImageValueError::from_image_value_error (
								image_value_error
							)
						)
					);
				}
			}
		},
		// Creates a Uri
		contack::uri::Uri::Url{url} => {
			Ok(
				ImageValue::from_uri (
					vcard::values::uri::URI::from_string (
						url.to_string()
					)?
				)
			)
		}
	}

}

fn vset<
	T :
		core::hash::Hash +
		Eq +
		> (
	property : T
) -> Result<Option<Set<T>>, Box<dyn Error>> where T:
	vcard::validators::ValidatedWrapper {
	Ok(
		Some(
			Set::from_hash_set({
			let mut hash_set = HashSet::new();
			hash_set.insert(property);
			hash_set
			})?
		)
	)
}

fn preference_from_int(pref : u8) -> Result<Preference, Box<dyn Error>> {
	Ok(
		Preference::from_preference_value (
			PreferenceValue::from_number(pref)?
		)
	)
}

fn contack_type_to_vcard_type (
	typ : &contack::contact_information::Type
) -> Result<Type, Box<dyn Error>> {
	Ok ({
		// HashSet to store the type
		let mut hash_set = HashSet::new();

		// Adds the type to the hash set
		hash_set.insert ({
			match typ {
				// Work
				contack::contact_information::Type::Work =>
					TypeValue::Work,
				// Home
				contack::contact_information::Type::Home =>
					TypeValue::Home,
			}
		});

		Type::from_type_values (
			Set::from_hash_set(hash_set)?
		)
	})
}

fn contack_type_to_vcard_tel_type (
	typ : &contack::contact_information::Type
) -> Result<TypeWithTelType, Box<dyn Error>> {
	Ok ({
		// HashSet to store the type
		let mut hash_set = HashSet::new();

		// Adds the type to the hash set
		hash_set.insert ({
			match typ {
				// Work
				contack::contact_information::Type::Work =>
					TypeValueWithTelephoneType::Work,
				// Home
				contack::contact_information::Type::Home =>
					TypeValueWithTelephoneType::Home,
			}
		});

		TypeWithTelType::from_type_values (
			Set::from_hash_set(hash_set)?
		)
	})
}

// Creates a PropertyID from two u8
fn property_id_from_string(
	pid : &str,
) -> Result<Option<PropertyID>, Box<dyn Error>> {
	Ok(
		Some(
			PropertyID::from_ids ({
				// Creates a hashset
				let mut hash_set = HashSet::new();

				// Adds things to it
				for n in hex::decode(pid)? {
					hash_set.insert (
						match PropertyIDValue::from_u8 (
							n % 8,
							Some((n + 8) % 8)
						) {
							Ok(prop) => prop,
							Err(_) => return Err(
								Box::from("PropertyIdValuError")
							)
						}
					);
					hash_set.insert (
						match PropertyIDValue::from_u8 (
							(n / 16) % 8,
							Some(((n / 16) + 8) % 8)
						) {
							Ok(prop) => prop,
							Err(_) => return Err(
								Box::from("PropertyIdValuError")
							)
						}
					);
				}

				Set::from_hash_set(hash_set)?
			})
		)
	)
}

fn contack_address_to_vcard_address (
	address : &contack::address::Address
) -> Result<Address, Box<dyn Error>> {
	let mut adr = Address::from_address_value(
		AddressValue::from_components (
			None,
			None,
			op_string_to_comp (address.street.as_ref()),
			op_string_to_comp (address.locality.as_ref()),
			op_string_to_comp (address.region.as_ref()),
			op_string_to_comp (address.code.as_ref()),
			op_string_to_comp (address.country.as_ref()),
		)
	);
	adr.geo = contack_geo_to_vcard_geo(address.geo.as_ref())?;
	Ok(adr)
}

fn contack_geo_to_vcard_geo (
	geo : Option<&contack::address::Geo>
) -> Result<Option<Geo>, Box<dyn Error>> {
	match geo {
		// If the Geo is none return none
		None => Ok(None),
		// Otherwise create some longitudes and latitudes
		Some (geo) => {
			Ok ( Some(
				Geo::from_geo_value (
					GeoValue::LatLng(
						Latitude::from_number(geo.latitude)?,
						Longitude::from_number(geo.longitude)?
					)
				)
			) )
		}
	}
}