var fs = require('fs');
var crypto = require('crypto');
var Evernote = require('evernote').Evernote;
var xmlbuilder = require('xmlbuilder');
var _ = require('underscore');
var limit = require("simple-rate-limiter");
var exports = module.exports = {};



function getClient(authToken, isSandbox, isChina) {
    var client = new Evernote.Client({token: authToken, sandbox: isSandbox, china: isChina});

    var userStore = client.getUserStore();

    userStore.checkVersion(
        "Evernote EDAMTest (Node.js)",
        Evernote.EDAM_VERSION_MAJOR,
        Evernote.EDAM_VERSION_MINOR,
        function (err, versionOk) {
            console.log("Is my Evernote API version up to date? " + versionOk);
            console.log();
            if (!versionOk) {
                process.exit(1);
            }
        }
    );

    return client;
}


function textToENML(text) {
    var xml = xmlbuilder.create('en-note', {version: '1.0', encoding: 'UTF-8', standalone: false},
        {sysID: 'http://xml.evernote.com/pub/enml2.dtd'},
        {allowSurrogateChars: true});


    xml.ele("pre").txt(text);

    var xmlExportedString = xml.end({
        pretty: true,
        indent: '  ',
        newline: '\n',
        allowEmpty: false
    });
    return xmlExportedString;
}


function EvernoteApi() {
    var authToken = "S=s1:U=9321a:E=16008a5feec:C=158b0f4d080:P=1cd:A=en-devtoken:V=2:H=3046fcbba2441bc4fc0f71e87948db05";
    var isSandbox = true;
    var isChina = false;

    if (authToken == "your developer token") {
        console.log("Please fill in your developer token in a OS Env variable named EVERNOTE_AUTH_TOKEN");
        console.log("To get a developer token, visit https://sandbox.evernote.com/api/DeveloperToken.action");
        process.exit(1);
    }

    var client = getClient(authToken, isSandbox, isChina)
    var noteStore = client.getNoteStore();
    var notebooksCache = {};
    var reqCounter = 0;

    function _createNote(notebookGuid, title, content, created) {
        return new Promise((resolve, reject) => {
            var note = new Evernote.Note();
            note.notebookGuid = notebookGuid;
            note.title = title;
            note.content = textToENML(content);
            note.created = created;

            noteStore.createNote(note, function (err, createdNote) {
                if (err) {
                    console.log("err: " + JSON.stringify(err));
                    // process.exit(1);
                    err.note = note
                    reject(err);
                } else {
                    console.log('note created')
                    resolve(createdNote)
                }

            });
        })
    }

    this.createNote = function (notebookName, title, content, created) {
        return new Promise((resolve, reject) => {
            reqCounter++;

            if (notebooksCache[notebookName]) {
                console.log("reqCounter: " + reqCounter + " using notebook cache");
                _createNote(notebooksCache[notebookName].guid, title, content, created)
                    .then((note) => {
                        resolve(note)
                    })
                    .catch((err) => {
                        reject(err)
                    })


            } else {
                console.log("reqCounter: " + reqCounter + " without notebook cache");
                noteStore.listNotebooks(function (err, notebooks) {

                    if (err) {
                        console.log("err:" + JSON.stringify(err));
                        // process.exit(1);
                        reject(err)
                    }

                    var notebook = null;
                    for (var i in notebooks) {
                        if (notebooks[i].name === notebookName) {
                            notebook = notebooks[i];
                            break;
                        }
                    }
                    if (!notebook) {
                        console.log("notebook named " + notebookName + " not found");
                        // process.exit(1);
                        reject(new Error("notebook named " + notebookName + " not found"))
                    }
                    notebooksCache[notebookName] = notebook;
                    _createNote(notebook.guid, title, content, created)
                        .then((note) => {
                            resolve(note)
                        })
                        .catch((err) => {
                            reject(err)
                        })


                });
            }
        })
    }
    // .to(1).per(1000);


}


exports.EvernoteApi = EvernoteApi;

@@ -3459,119 +3459,8 @@
 ) %7B%0A
-                        console.log(%22err:%22 + JSON.stringify(err));%0A                        // process.exit(1);%0A
     
@@ -3553,58 +3553,37 @@
 k = 
-null;%0A                    for (var i in notebooks)
+(notebooks %7C%7C %5B%5D).find((n) =%3E
  %7B%0A 
@@ -3609,24 +3609,16 @@
     
-if (notebooks%5Bi%5D
+return n
 .nam
@@ -3635,19 +3635,16 @@
 bookName
-) %7B
 %0A       
@@ -3660,290 +3660,48 @@
     
-        notebook = notebooks%5Bi%5D;%0A                            break;%0A                        %7D%0A                    %7D%0A                    if (!notebook) %7B%0A                        console.log(%22notebook named %22 + notebookName + %22 not found%22);%0A                        // process.exit(1);
+%7D)%0A%0A                    if (!notebook) %7B
 %0A   
@@ -3801,33 +3801,44 @@
                %7D
-%0A
+ else %7B%0A    
                 
@@ -3882,16 +3882,20 @@
 tebook;%0A
+    
         
@@ -3974,32 +3974,36 @@
                 
+    
 .then((note) =%3E 
@@ -3996,32 +3996,36 @@
 hen((note) =%3E %7B%0A
+    
                 
@@ -4066,35 +4066,42 @@
                 
-%7D)%0A
+    %7D)%0A   
                 
@@ -4100,32 +4100,33 @@
                 
+ 
 .catch((err) =%3E 
@@ -4119,32 +4119,36 @@
 atch((err) =%3E %7B%0A
+    
                 
@@ -4187,35 +4187,60 @@
                 
-%7D)%0A
+    %7D)%0A                    %7D
 %0A%0A              
@@ -4280,33 +4280,8 @@
   %7D%0A
-    // .to(1).per(1000);%0A
 %0A%0A%7D%0A

fix error and use array.find