const passport = require('passport'),
    FacebookStrategy = require('passport-facebook'),
    debug = require('debug')('urer:FacebookLogin'),
    UserModel = require('../../model/user'),
    fbPrefix = "https://www.facebook.com/profile.php?id=",
    async = require('async'),
    sparqlHelper = require('../../helper/sparql'),
    facebookPermission = [
        'email',
        'user_likes',
        'user_friends',
        'public_profile',
        'user_about_me',
        'user_actions.books',
        'user_actions.music',
        'user_actions.video',
        'user_location',
        'user_hometown',
        'rsvp_event',
        'user_events'
    ];

function insertInterest(meta) {
    debug('Interest insert', meta);
    sparqlHelper.insert_new_interest(meta, function (err, res) {
        if (err) {
            debug('Error inserting interest', err);
        }
        else {
            debug('Interest inserted!');
        }
    })
}

function insertFriend(meta) {
    debug('Friend insert', meta);
    sparqlHelper.insert_new_friend(meta, function (err, res) {
        if (err) {
            debug('Error inserting interest', err);
        }
        else {
            debug('Friend inserted!');
        }
    })
}

function insertAllFriends(userData, cb) {
    userData.friends && userData.friends.forEach(function (friend) {
        insertFriend({
            service_homepage: 'facebook.com',
            profile_link: friend.fb_profile,
            userID: userData.id
        });
    });

    setTimeout(cb, 3000);
}

function insertAllInterest(userData, cb) {
    userData.movies && userData.movies.forEach(function (movie) {
        insertInterest({
            category: 'movie',
            name: movie.name,
            link: movie.fb_profile,
            id: movie.id,
            userID: userData.id
        });
    });
    userData.music && userData.music.forEach(function (movie) {
        insertInterest({
            category: 'music',
            name: movie.name,
            link: movie.fb_profile,
            id: movie.id,
            userID: userData.id
        });
    });
    userData.books && userData.books.forEach(function (movie) {
        insertInterest({
            category: 'book',
            name: movie.name,
            link: movie.fb_profile,
            id: movie.id,
            userID: userData.id
        });
    });

    setTimeout(cb, 3000);
}

function insertUser(userData, cb) {
    sparqlHelper.insert_user(userData, function (err, res) {
        if (err) {
            debug('Error inserting user', err);
            return cb(err);
        }
        else {
            debug('User inserted!');
            return cb(null, res);
        }
    })
}
passport.serializeUser(function (user, cb) {
    user.service_homepage = "facebook.com";
    let newUser = new UserModel(user._json);
    debug(newUser.getData());
    async.series([
        async.apply(insertUser, newUser),
        async.apply(insertAllInterest, newUser),
        async.apply(insertAllFriends, newUser)
    ], function (err, res) {
        debug('User id ', user.id);
        async.series([
            async.apply(sparqlHelper.recommend_music, user.id),
            async.apply(sparqlHelper.recommend_books, user.id),
            async.apply(sparqlHelper.recommend_books, user.id),
        ], function (err, res) {
            if (err) {
                debug(err);
            }
            else {
                debug(res);
            }
        });
        cb(null, user);
    })
});

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

passport.use(new FacebookStrategy(env.config.external_login.facebook,
    function (accessToken, refreshToken, profile, cb) {
        debug(profile.id);
        profile.accessToken = accessToken;
        cb(null, profile);
    }
));

module.exports.facebookAuth = function (req, res, next) {
    let authHandler = passport.authenticate('facebook', {
        scope: facebookPermission
    });
    authHandler(req, res, next);
};

module.exports.facebookAuthCallback = function (req, res, next) {
    debug('Facebook callback');
    let authHandler = passport.authenticate('facebook', {failureRedirect: '/login'});
    authHandler(req, res, next);
};
