var jwt          = require('jsonwebtoken');
var config       = require('../config.js');
var request      = require('request');
var Model        = require('../models');


var Login = {
  Login: this,
  makeJWT: function(user) {
    var token = jwt.sign({
      // Look at the spec to add more things in here
      userName: user.userName,
      userId: user._id
    }, config.jwtSecret);

    return token;
  },

  verifyFBToken: function(req, res, next) {
    var fbAccessToken = req.params.accessToken;

    // get user info using token
    var endpoint = 'https://graph.facebook.com/me?access_token=';
    request(endpoint + fbAccessToken, function(err, response, body){

      var initialResponse = JSON.parse(body);
      var fbId = initialResponse.id;
      if (fbId != null || fbId != undefined) {
        Model.User.findOne({ facebookId: fbId }, function(err, user) {
          if (err) {
            req.status(500);
            req.errorMessage = "Error retrieving user with Facebook Id " + fbId;
            next();
          } else if (user) {
            req.jwt = Login.makeJWT(user);
            next();
          } else {
            // New user!!!
            // Get profile picture url
            request('http://graph.facebook.com/v2.8/' + fbId + '/picture?redirect=0&type=large', function(err, response, body){
              var result = JSON.parse(body);
              var fbPicUrl = result.data.url;
              // Make a cool cyber name for surfin on the net
              var nameArray = initialResponse.name.split(' ');
              var userName = nameArray.shift().toLowerCase();
              for (part in nameArray) {
                userName += nameArray[part];
              }
              var newUser = new Model.User({
                facebookId: fbId,
                userName: userName,
                picUrl: fbPicUrl,
                recentlyListenedItems: [],
                favorites: 0
              });



              newUser.save(function(err, newUser){
                if (err) {
                  console.log(err);
                }
                if (!err) {
                  req.jwt = Login.makeJWT(newUser);
                  next();
                }
              })
            })
          }
        });
      }

    })
  },

  findOrCreateFBUser: function(accessToken, refreshToken, profile, cb) {
    Model.User.findOne({ facebookId: profile.id }, function (err, user) {
      if (user) {
        return cb(err, user);
      } else {
        // New user!!!
        // Get profile picture url
        request('http://graph.facebook.com/v2.8/' + profile.id + '/picture?redirect=0&type=large', function(err, response, body){
          var result = JSON.parse(body);
          var fbPicUrl = result.data.url;
          // Make a cool cyber name for surfin on the net
          var nameArray = profile.displayName.split(' ');
          var userName = nameArray.shift().toLowerCase();
          for (part in nameArray) {
            userName += nameArray[part];
          }
          var newUser = new Model.User({
            facebookId: profile.id,
            userName: userName,
            picUrl: fbPicUrl,
            recentlyListenedItems: [],
            favorites: 0
          });



          newUser.save(function(err, newUser){
            return cb(err, newUser);

          })
        })
      }

    });

  }
};

module.exports = Login;
