var voicejs = require('../voice.js');
var fs = require('fs');

var client = new voicejs.Client({
	email: process.argv[2] || 'email@gmail.com',
	password: process.argv[3] || 'password',
	tokens: require('./tokens.json')
});

// beautify
String.prototype.padLeft = function(length){
	return new Array(length - this.length + 1).join(' ') + this; 
}

// Helper function to indicate whether an Array contains an entry
// Used to check if a conversation has a certain label, such as convo.is('starred')
Array.prototype.is = function(entry){
	return !!~this.indexOf(entry);
}


// Get the 5 latest voicemails. Display transcripts and download the audio to a file.
client.get('voicemail', {limit: 5}, function(error, response, data){
	if(error){
		return console.log(error);
	}
	
	if(!data || !data.conversations_response || !data.conversations_response.conversation){ return console.log('No conversations.')}
	
	console.log('\nLatest voicemails:');
	
	// Display the conversations indicating if they have been read or starred and whether it's a text or voicemail
	data.conversations_response.conversation.forEach(function(convo, index){
		console.log('\n%s %s. %s %s %s', 
			convo.read ? ' ' : '+', 
			(index+1+'').padLeft(3),  
			convo.phone_call[0].contact.phone_number_formatted.padLeft(15),
			new Date(convo.conversation_time).toISOString().replace(/[ZT]/g,' ').substr(0,16).padLeft(18),
			convo.label.is('starred') ? '*' : ' '
		);
		if(convo.phone_call[0].transcript && convo.phone_call[0].transcript.word_tokens){
			console.log(convo.phone_call[0].transcript.word_tokens.map(function(entry){ return entry.word}).join(' '));
		}
		
        // Download the voicemail mp3
		client.getAudio({id: convo.id, format: 'mp3'}, function(err, res, data){
			if(err){
				console.log(err)
				return;
			}

			var fileName = './' + convo.id + '.mp3';
			fs.writeFileSync(fileName, data);
		});
	});
});
@@ -763,17 +763,16 @@
 or);%0A%09%7D%0A
-%09
 %0A%09if(!da
@@ -850,16 +850,21 @@
 ersation
+group
 )%7B retur
@@ -939,17 +939,55 @@
 ils:');%0A
-%09
+%0A    //status 0 unread%0A%09//status 1 read
 %0A%09// Dis
@@ -1132,16 +1132,21 @@
 ersation
+group
 .forEach
@@ -1215,20 +1215,35 @@
 %09%09convo.
-read
+call%5B0%5D.status == 1
  ? ' ' :
@@ -1288,30 +1288,24 @@
 %09%09convo.
-phone_
 call%5B0%5D.
 contact.
@@ -1300,16 +1300,8 @@
 %5B0%5D.
-contact.
 phon
@@ -1312,18 +1312,8 @@
 mber
-_formatted
 .pad
@@ -1352,16 +1352,29 @@
 ersation
+.conversation
 _time).t
@@ -1442,16 +1442,29 @@
 %09%09convo.
+conversation.
 label.is
@@ -1491,16 +1491,23 @@
 ' '%0A%09%09);
+ %0A%09    
 %0A%09%09if(co
@@ -1506,30 +1506,24 @@
 %0A%09%09if(convo.
-phone_
 call%5B0%5D.tran
@@ -1534,30 +1534,24 @@
 pt && convo.
-phone_
 call%5B0%5D.tran
@@ -1592,22 +1592,16 @@
 g(convo.
-phone_
 call%5B0%5D.
@@ -1750,16 +1750,29 @@
 : convo.
+conversation.
 id, form
@@ -1891,16 +1891,29 @@
 + convo.
+conversation.
 id + '.m

update voicemail example to work with latest voice.js changes