var mongoose = require('mongoose');
var passport = require('passport');
var config = require('../config/database');
require('../config/passport')(passport);
var express = require('express');
var jwt = require('jsonwebtoken');
var router = express.Router();
var User = require("../models/user");
var FileMongo = require("../models/FileMongo");
var Book = require("../models/book");

var multer = require('multer');
var upload = multer({ dest: './public/' });

/* GET home page. */
router.get('/', function(req, res, next) {
  res.send('Express RESTful API');
});


router.post('/signup', function(req, res) {
  if (!req.body.username || !req.body.password) {
    res.json({success: false, msg: 'Please pass username and password.'});
  } else {
    var newUser = new User({
      username: req.body.username,
      password: req.body.password
    });
    // save the user
    newUser.save(function(err) {
      if (err) {
        return res.json({success: false, msg: 'Username already exists.'});
      }
      res.json({success: true, msg: 'Successful created new user.'});
    });
  }
});

/* SAVE FILE */
router.post('/uploadFileMongo', function(req, res, next) {
  console.log('req.body:  :: ' + req.body.uid);
  FileMongo.create(req.body, function (err, post) {
    if (err){
      console.log('err:  :: ' + err);
      return next(err);
    }
    res.json(post);
  });
});

/* DELETE FILE */
router.post('/deleteFileMongo', function(req, res, next) {

  FileMongo.remove(req.body, function (err, post) {
    if (err){
      return next(err);
    }
    res.json(post);
  });
});

router.post('/signin', function(req, res) {
  User.findOne({
    username: req.body.username
  }, function(err, user) {
    if (err) throw err;

    if (!user) {
      res.status(401).send({success: false, msg: 'Authentication failed. User not found.'});
    } else {
      // check if password matches
      user.comparePassword(req.body.password, function (err, isMatch) {
        if (isMatch && !err) {
          console.log('req.user.username logggggg ::: ' + JSON.stringify(user));
          // if user is found and password is right create a token
          var token = jwt.sign(user.toJSON(), config.secret);
          // return the information including token as JSON
          res.json({success: true, token: 'JWT ' + token});
        } else {
          res.status(401).send({success: false, msg: 'Authentication failed. Wrong password.'});
        }
      });
    }
  });
});


router.post('/book', passport.authenticate('jwt', { session: false}), function(req, res) {
  var token = getToken(req.headers);
  if (token) {

    var newBook = new Book({
      isbn: req.body.isbn,
      title: req.body.title,
      author: req.body.author,
      publisher: req.body.publisher
    });

    newBook.save(function(err) {
      if (err) {
        return res.json({success: false, msg: 'Save book failed.'});
      }
      res.json({success: true, msg: 'Successful created new book.'});
    });
  } else {
    return res.status(403).send({success: false, msg: 'Unauthorized.'});
  }
});
/*
router.post('/book/file', function(req, res) {
  if(req.files){
    //var file = req.files.filename;
    //var filename = req.files.filename.name;

    console.log(req.files);
  }
});
*/
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, './public/')
  },
  filename: function (req, file, cb) {
    cb(null, file.originalname)
  }
});

//post qui va stocker la photo du user ajoute dans le register , multer permet de definir le dossier serveur dans lequel seront stockes les photos
router.post('/upload' , multer({storage: storage}).array("public[]", 12) ,function(req,res,next){

  console.log("req.files[0].fieldname: "+req.files[0].fieldname);//ok
  console.log("req.files[0].originalname: "+req.files[0].originalname);//ok
  console.log("req.files.filename: "+req.files[0].filename);//ok
  console.log("req.files.path: "+req.files[0].path);//ok
  console.log("req.files.size: "+req.files[0].size);//ok
  res.send(req.files);

});

router.get('/allUserFile', passport.authenticate('jwt', { session: false}), function(req, res) {
  var token = getToken(req.headers);

  if (token) {
    console.log('oooooo : ' + req.user._id + ' ::: kaka : ' + req.user.username);
    FileMongo.find({
      idUser: req.user._id,
      owner: req.user.username
    }, function(err, file) {
      console.log('userrrr baa : ' + JSON.stringify(file));
      res.json(file);
    });
  } else {
    return res.status(403).send({success: false, msg: 'Unauthorized.'});
  }
});


router.get('/book', passport.authenticate('jwt', { session: false}), function(req, res) {
  var token = getToken(req.headers);

  if (token) {
    console.log('oooooo : ' + req.user._id + ' ::: kaka : ' + req.user.username);
    FileMongo.find({
      idUser: req.user._id,
      owner: req.user.username
    }, function(err, file) {
      console.log('userrrr baa : ' + JSON.stringify(file));
        });
    console.log('req.user.username yiiiiii ::: ' + req.user.username);
    res.json(req.user);
    /*
    Book.find(function (err, books) {
      if (err) return next(err);
      res.json(books);
    });*/
  } else {
    return res.status(403).send({success: false, msg: 'Unauthorized.'});
  }
});

router.get('/book/file',  function(req, res) {

  res.sendFile(__dirname + '/api/book');

});


getToken = function (headers) {
  if (headers && headers.authorization) {
    var parted = headers.authorization.split(' ');
    if (parted.length === 2) {
      return parted[1];
    } else {
      return null;
    }
  } else {
    return null;
  }
};

module.exports = router;
