'use strict';

const express = require('express');
const router = express.Router();

const Twitter = require('twitter');
const watson = require('watson-developer-cloud');

const Personality = require('../models/personality');

const personalityInsightsApiVersion = 'v2';

const personalityInsightsClient = watson.personality_insights({
  username: process.env.O3_BARISTA_INSIGHTS_USERNAME,
  password: process.env.O3_BARISTA_INSIGHTS_PASSWORD,
  version: personalityInsightsApiVersion
});

const twitterClient = new Twitter({
  consumer_key: process.env.O3_BARISTA_TWITTER_CONSUMER_KEY,
  consumer_secret: process.env.O3_BARISTA_TWITTER_CONSUMER_SECRET,
  access_token_key: process.env.O3_BARISTA_TWITTER_ACCESS_TOKEN_KEY,
  access_token_secret: process.env.O3_BARISTA_TWITTER_ACCESS_TOKEN_SECRET
});

router.put('/:twitteruser', (req, res) => {
  const username = req.params.twitteruser;

  fetchTwitterFeed(username)
    .then(result => {
      personalityInsightsClient.profile({
        text: result,
        language: 'en'
      }, (err, response) => {
        if (err) {
          console.log('error:', err);
        } else {
          savePersonalityResponse(username, response);

          const personalityArray = parsePersonalityResponse(response);
          console.log(personalityArray);
          res.json(personalityArray);
        }
      });
    })
    .catch(e => {
      console.log(e);
    });
});

function fetchTwitterFeed(username) {
  return new Promise(resolve => {
    const params = { screen_name: username, count: 5000 };
    twitterClient.get('statuses/user_timeline', params, (error, tweets) => {
      if (error) {
        console.error(error);
      }

      if (!error) {
        let test;
        for (let i = 0; i < tweets.length; i++) {
          console.log(tweets[i].text);
          test += tweets[i].text;
        }
        resolve(test);
      }
    });
  });
}

function savePersonalityResponse(username, response) {
  const personality = new Personality({
    twitter_handle: username,
    raw_response: response,
    api_version: personalityInsightsApiVersion
  });

  personality.save(err => {
    if (err) {
      console.log(err);
    }
  });
}

function parsePersonalityResponse(response) {
  const array = [];
  const i = response.tree.children;

  i.forEach(thing => {
    thing.children.forEach(thing2 => {
      const obj = { id: thing2.id, percentage: thing2.percentage };
      array.push(obj);
      thing2.children.forEach(thing4 => {
        const obj = { id: thing4.id, percentage: thing4.percentage };
        array.push(obj);
      });
    });
  });

  return array;
}

module.exports = router;

@@ -2239,17 +2239,23 @@
   const 
-a
+resultA
 rray = %5B
@@ -2261,17 +2261,252 @@
 %5B%5D;%0A
+%0A
   
-const i
+// There are only 3 child objects as the value of the tree property for now.%0A  // These serve as the aspects which will lead to an insight.%0A  // Personality, Needs, Values are the 3 aspects%0A  // This may change in the future.%0A  const aspects
  = r
@@ -2535,38 +2535,127 @@
 %0A%0A  
-i.
 for
-Each(thing =%3E %7B%0A    thing
+ (let i = 0; i %3C aspects.length; i++) %7B%0A    const aspect = aspects%5Bi%5D;%0A%0A    // loop for traits of aspects%0A    aspect
 .chi
@@ -2669,21 +2669,20 @@
 orEach(t
-hing2
+rait
  =%3E %7B%0A  
@@ -2683,35 +2683,43 @@
 %3E %7B%0A      const 
-obj
+traitObject
  = %7B id: thing2.
@@ -2712,21 +2712,20 @@
  %7B id: t
-hing2
+rait
 .id, per
@@ -2734,21 +2734,20 @@
 ntage: t
-hing2
+rait
 .percent
@@ -2755,25 +2755,31 @@
 ge %7D;%0A      
-a
+resultA
 rray.push(ob
@@ -2780,26 +2780,80 @@
 ush(
-obj
+traitObject
 );%0A
+%0A
       
-thing2
+// loop for traits of traits of aspects%0A      trait
 .chi
@@ -2866,22 +2866,24 @@
 forEach(
-thing4
+subTrait
  =%3E %7B%0A  
@@ -2894,19 +2894,30 @@
   const 
-obj
+subTraitObject
  = %7B id:
@@ -2917,22 +2917,24 @@
 = %7B id: 
-thing4
+subTrait
 .id, per
@@ -2946,14 +2946,16 @@
 ge: 
-thing4
+subTrait
 .per
@@ -2973,17 +2973,23 @@
         
-a
+resultA
 rray.pus
@@ -2990,19 +2990,30 @@
 ay.push(
-obj
+subTraitObject
 );%0A     
@@ -3024,26 +3024,24 @@
 %0A    %7D);%0A  %7D
-);
 %0A%0A  return a
@@ -3039,17 +3039,23 @@
  return 
-a
+resultA
 rray;%0A%7D%0A

refactor the parsing of the personality response by renaming variables and restructuring the looping for clarity