var express  = require("express");
var path =  require("path");
var bodyParser = require("body-parser");
var http = require("http").Server(express);
var passport = require('passport');
var Strategy = require('passport-facebook').Strategy;
var db = require("./database/mongo");
var crypto = require("crypto");

var port = 13085;

var solve = require("./controller/solve");


passport.use(new Strategy({
    clientID: 1745702722349141,
    clientSecret: '0492d45d0130f447a262a12b026bb80c',
    callbackURL: 'http://rosetaxis.dedicated.co.za:13085/login/facebook/return', 
    enableProof: true,
    profileFields: ['id', 'emails', "first_name", "gender", "last_name"]
  },
  function(accessToken, refreshToken, profile, cb) {
    // In this example, the user's Facebook profile is supplied as the user
    // record.  In a production-quality application, the Facebook profile should
    // be associated with a user record in the application's database, which
    // allows for account linking and authentication with other identity
    // providers.
    console.log(profile);
    return cb(null, profile);
  }));


// Configure Passport authenticated session persistence.
//
// In order to restore authentication state across HTTP requests, Passport needs
// to serialize users into and deserialize users out of the session.  In a
// production-quality application, this would typically be as simple as
// supplying the user ID when serializing, and querying the user record by ID
// from the database when deserializing.  However, due to the fact that this
// example does not have a database, the complete Facebook profile is serialized
// and deserialized.

var raw = "";
passport.serializeUser(function(user, cb) {
  console.log("USER : ");
  //raw = user._raw.replace(":","=").replace(",","&");
  raw = user._raw.replace("\"","&");
  var facebookid = user.id;
  var surname = user.name.familyName;
  var name = user.name.givenName;
  var _email = user.emails[0].value;
  raw = "name="+ name + "&surname="+ surname + "&email="+ _email;

  db.users.find({email:_email},function(err,data){
      if(!err)
      {
          if(data.length < 1)
          {
              var _user = {};
              _user.name = name;
              _user.surname = surname;
              _user.email = _email;
              _user.facebookid= facebookid;
              _user.usercode = surname.substring(0, 1).toUpperCase()+name.substring(0, 1).toUpperCase()+  crypto.randomBytes(3).toString("hex").toUpperCase();
              db.users.insert(_user);
          }
      }
  })

  console.log(raw);
  cb(null, user);
});

passport.deserializeUser(function(obj, cb) {
  cb(null, obj);
});


var app = express();

var nocache = require('nocache')
app.use(nocache())


//view engine
app.set("views",path.join(__dirname,"views"));
app.set("views engine","ejs");
app.engine("html",require("ejs").renderFile);

//set static folder
app.use(express.static(path.join(__dirname,"client")));

//body parser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(require('morgan')('combined'));
app.use(require('cookie-parser')());
app.use(require('express-session')({ secret: 'keyboard cat', resave: true, saveUninitialized: true }));

app.use(passport.initialize());
app.use(passport.session());



app.use("/",solve);
var page = "";
app.get('/login/facebook/:page',
  passport.authenticate('facebook', { scope: [ 'email'] })
);

app.get('/login/facebook/return', 
  passport.authenticate('facebook', { failureRedirect: '/login' }),
  function(req, res) {
    res.redirect('http://math.sipnet.co.za?page=validauth&'+raw);
   
  });

app.listen(port,function(){
    console.log("server started on port " +  port);
    //sendNotofication();
    
});

