
/*
This is pretty simplistic at the moment, since it doesn't handle references. More work is needed to actually
*/

let envOK = (
   MSJSONDataArchiver !== undefined
&& MSJSONDictionaryUnarchiver !== undefined
);

function appVersion() {
  if (NSBundle !== undefined) {
    return NSBundle.mainBundle().infoDictionary().CFBundleShortVersionString;
  } else {
    return undefined;
  }
}

const _checkEnv = () => {
  if (!envOK) {
    throw new Error("sketchapp-json-plugin needs to run within the correct version of Sketch. You are running " + appVersion());
  }
}

export function appVersionSupported() {
  return envOK;
}

// Converts an object, eg from context.selection into its JSON string representation
export function toSJSON(sketchObject) {
  _checkEnv();
  if (!sketchObject) {
    return null;
  }
  const imm = sketchObject.immutableModelObject();
  return MSJSONDataArchiver.archiveStringWithRootObject_error_(imm, null);
}

export function fromSJSON(json) {
  _checkEnv();
  const dict = JSON.parse(json);
  if (!dict) return null;
  if (dict._class.length <= 0) {
    return null;
  }
  return fromSJSONDictionary(dict);
}

// Takes a Sketch JSON tree and turns it into a native object. May throw on invalid data
export function fromSJSONDictionary(jsonTree) {
  _checkEnv();
  const decoded = MSJSONDictionaryUnarchiver.alloc().initForReadingFromDictionary(jsonTree).decodeRoot();
  const mutableClass = decoded.class().mutableClass();
  return mutableClass.alloc().initWithImmutableModelObject(decoded);
}

@@ -125,14 +125,20 @@
 OK =
- (
 %0A   
+(typeof 
 MSJS
@@ -148,32 +148,33 @@
 ataArchiver !== 
+'
 undefined%0A&& MSJ
@@ -170,11 +170,21 @@
 ined
+')
 %0A&&
+ (typeof
  MSJ
@@ -207,24 +207,25 @@
 rchiver !== 
+'
 undefined%0A);
@@ -225,11 +225,10 @@
 ined
-%0A);
+')
 %0A%0Afu
@@ -255,16 +255,23 @@
 %7B%0A  if (
+typeof 
 NSBundle
@@ -275,16 +275,17 @@
 dle !== 
+'
 undefine
@@ -285,16 +285,17 @@
 ndefined
+'
 ) %7B%0A    

fix checking global object presence