var request = require('request-promise').defaults({simple: false});
var config = require('config');
var Promise = require('bluebird');
var _ = require('lodash');
var auth = require('../helper/auth');
var drive = require('../helper/drive');

var trello = exports;

trello.createTrelloBoard = (contractor, credentials) => {
  return trello.addBoard(contractor)
    .then((boardId) => {
      var toDoAfterBoardCreated = [];
      for (var member of config.get('trello.team.members')) {
        toDoAfterBoardCreated.push(trello.addBoardMember(boardId, member.id));
      }
      toDoAfterBoardCreated.push(trello.addList(boardId, 'Done'));
      toDoAfterBoardCreated.push(trello.addList(boardId, 'In Progress'));
      toDoAfterBoardCreated.push(trello.addList(boardId, 'On Deck'));
      toDoAfterBoardCreated.push(
        Promise.all([trello.addList(boardId, 'To Do'), drive.getTasksFromFile(credentials)])
          .spread( (listId, tasks) => {
            var cardsToAdd = [];
            for (var task of tasks) {
              var description = task.split(',')[0];
              var memberName = task.split(',')[1];
              cardsToAdd.push(trello.addCard(listId, description, memberName));
            }
            return Promise.all(cardsToAdd);
          })
      );

      return Promise.all(toDoAfterBoardCreated);
    })
    .then(() => {
        return Promise.resolve({'text': 'Created board on Trello', 'status': 'success'});
      }
    )
    .catch((err) => {
      console.log(err);
      return Promise.resolve({'text': 'Problem creating board on Trello', 'status': 'failure'});
    });
};

trello.addBoard = (contractor) => {
  var trelloUrl = config.get('trello.baseUrl') + '/boards';
  var boardName = 'Onboarding: ' + contractor.getFullName();

  return request.post({
    url: trelloUrl,
    qs: {
      token: config.get('trello.token'),
      key: config.get('trello.key')
    },
    json: true,
    body: {
      'name': boardName,
      'defaultLists': false,
      'idOrganization': config.get('trello.team.id'),
      'prefs_permissionLevel': 'org'
    }
  })
    .then((response) => {
      var responseData = JSON.parse(JSON.stringify(response));
      if ('id' in responseData) {
        return responseData.id;
      } else {
        throw new Error('No id in create board response: ' + responseData);
      }
    });
};

trello.addBoardMember = (boardId, memberId) => {
  var trelloUrl = config.get('trello.baseUrl') + '/boards/' + boardId + '/members/' + memberId;

  return request.put({
    url: trelloUrl,
    qs: {
      token: config.get('trello.token'),
      key: config.get('trello.key')
    },
    json: true,
    body: {
      'type': 'admin',
    }
  })
    .then((response) => {
      var responseData = JSON.parse(JSON.stringify(response));
      if ('id' in responseData) {
        return responseData.id;
      } else {
        throw new Error('No id in add member response: ' + responseData);
      }
    });
};

trello.addList = (boardId, listName) => {
  var trelloUrl = config.get('trello.baseUrl') + '/lists';

  return request.post({
    url: trelloUrl,
    qs: {
      token: config.get('trello.token'),
      key: config.get('trello.key')
    },
    json: true,
    body: {
      'name': listName,
      'idBoard': boardId
    }
  })
    .then((response) => {
      var responseData = JSON.parse(JSON.stringify(response));
      if ('id' in responseData) {
        return responseData.id;
      } else {
        throw new Error('No id in create list response: ' + responseData);
      }
    });
};

trello.addCard = (listId, description, memberName) => {
  var trelloUrl = config.get('trello.baseUrl') + '/cards';

  return request.post({
    url: trelloUrl,
    qs: {
      token: config.get('trello.token'),
      key: config.get('trello.key')
    },
    json: true,
    body: {
      'name': description,
      'idList': listId,
      'idMembers': [trello.getMemberId(memberName)]
    }
  })
    .then((response) => {
      var responseData = JSON.parse(JSON.stringify(response));
      if ('id' in responseData) {
        return responseData.id;
      } else {
        throw new Error('No id in create card response: ' + responseData);
      }
    });
};

trello.getMemberId = (memberName) => {
  var member = _.find(config.get('trello.team.members'), {'name': memberName });
  if (typeof member !== 'undefined') {
    return member.id;
  } else {
    return "";
  }
};
@@ -387,137 +387,107 @@
     
-var toDoAfterBoardCreated = %5B%5D;%0A      for (var member of config.get('trello.team.members')) %7B%0A        toDoAfterBoardCreated.push(
+return Promise.all(%0A        Promise.map(config.get('trello.team.members'), (member) =%3E %7B%0A          
 trel
@@ -523,25 +523,24 @@
 mber.id)
-)
 ;%0A      
 %7D%0A      
@@ -535,43 +535,22 @@
     
-%7D
+  %7D),
 %0A      
-toDoAfterBoardCreated.push(
+  
 trel
@@ -580,44 +580,52 @@
 ne')
-);
 %0A      
-toDoAfterBoardCreated.push(
+    .then(() =%3E %7B%0A            return 
 trel
@@ -662,122 +662,155 @@
 ss')
-);%0A      toDoAfterBoardCreated.push(trello.addList(boardId, 'On Deck'));%0A      toDoAfterBoardCreated.push(%0A       
+%0A          %7D)%0A          .then(() =%3E %7B%0A            return trello.addList(boardId, 'On Deck')%0A          %7D)%0A          .then(() =%3E %7B%0A            return
  Pro
@@ -905,16 +905,20 @@
     
+    
 .spread(
  (li
@@ -913,17 +913,16 @@
 .spread(
- 
 (listId,
@@ -950,64 +950,53 @@
     
-var cardsToAdd = %5B%5D;%0A            for (var task of 
+    return Promise.mapSeries(tasks, (
 task
-s
 )
+ =%3E
  %7B%0A 
@@ -1004,24 +1004,28 @@
             
+ 
+   
 var descript
@@ -1050,16 +1050,20 @@
 ,')%5B0%5D;%0A
+    
         
@@ -1123,24 +1123,19 @@
     
-cardsToAdd.push(
+    return 
 trel
@@ -1177,17 +1177,16 @@
 berName)
-)
 ;%0A      
@@ -1195,22 +1195,24 @@
     
-%7D%0A
     
+%7D);%0A
         
 retu
@@ -1211,109 +1211,36 @@
     
-return Promise.all(cardsToAdd);%0A          %7D)%0A      );%0A%0A      return Promise.all(toDoAfterBoardCreated
+      %7D)%0A          %7D)%0A      
 );%0A 
@@ -4246,17 +4246,16 @@
 mberName
- 
 %7D);%0A  if

Change createTrelloBoard to add cards in order