var Client = require('node-rest-client').Client;
const readline = require('readline');
const uuidv1 = require('node-uuid');

const PRODUCTID='904b7e35-33c8-45c6-8fd1-f5807b68f8e6';
const PRODUCTSECRET='bKN0NYfkkVHQx78A8rFCjS0z';
const AUTHORIZATIONURL='https://home.nest.com/login/oauth2?client_id=PRODUCTID&state=STATE';

var CLIENTSTATE=uuidv1().replace(/-/g,'');
var PINCODE='';
var ACCESSTOKEN='';
//const NEST_API_URL = 'https://developer-api.nest.com';
//const TOKEN_API_URL = 'https://api.home.nest.com/oauth2/access_token';
const NEST_API_URL = 'http://localhost:14253';
const TOKEN_API_URL = 'http://localhost:14253/oauth2/access_token';

console.log(AUTHORIZATIONURL.replace('STATE',CLIENTSTATE).replace('PRODUCTID',PRODUCTID));

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

rl.question('PINCODE? ', (answer) => {
    PINCODE = answer;
    var client = new Client();
    var args = {
	headers: {
	    "content-type": "application/x-www-form-urlencoded"
	},
	parameters: {
	    code: PINCODE,
	    client_id: PRODUCTID,
	    client_secret: PRODUCTSECRET,
	    grant_type: 'authorization_code'
	}
    }
    client.post(TOKEN_API_URL, args, function(data, response) {
	ACCESSTOKEN = data.access_token;

	var client = new Client();
	var args = {
            headers: {
		"Authorization": 'Bearer ' + ACCESSTOKEN
	    }
	};

	client.get(NEST_API_URL, args, function (data, response) {
	    var cameras=data.devices.cameras;

	    for (i=0; i<Object.keys(cameras).length; i++) {
		var cameraID = Object.keys(cameras)[i];
		var snapshotURL = cameras[cameraID].snapshot_url;
		var webURL = cameras[cameraID].web_url;
		console.log(cameraID+" snapshot_url: "+snapshotURL);
		console.log(cameraID+" web_url: "+webURL);
	    }
	});
	
	rl.close();

    });
});

