var express = require('express');
var app = express();
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var request = require('request');

var config = require('./config');

var Job = require('./models/Job');
var Movie = require('./models/Movie');

mongoose.connect(config.mongo.url);

app.use(express.static(__dirname + '/public'));
app.use(bodyParser.urlencoded({'extended':'true'}));
app.use(bodyParser.json());

/*
	/api/search
	Access Fandango's autocomplete API and convert their movie results to slugs that follow their format(sanitize name then append the ID).
*/
app.get('/api/search', function(req, res) {
    var q = req.query.q;
	request('https://www.fandango.com/api/search/autocompletemulti?q=' + q + '&callback=callback&_=' + Date.now(), function(error, response, body) {
		var movies = [];
		var callback = function(results) {
			results.forEach(function(result) {
				if (result.Type === 'Movie') {
					var movie_slug = result.Name;
					movie_slug = movie_slug.toLowerCase();
					movie_slug = movie_slug.replace(/[\s\(\)]/g, '');
					movie_slug = movie_slug + '-' + result.Id.substr(1);

					movies.push({
						id: result.Id,
						name: result.Name,
						slug: movie_slug
					});
				}
			});
			res.json(movies);
		}
		eval(body);
	});
    
});

app.get('/api/jobs', function(req, res) {
	Job.find().populate('movie').exec(function(err, jobs) {
		if (err) throw err;
		res.json(jobs);
	});
});

app.post('/api/jobs', function(req, res) {
    var new_job = req.body.job;
    var movie = req.body.movie;
    Job.findById(new_job._id).exec(function(err, job) {
    	if (!job) {
			var job = new Job({});
    	}
		job.theater = new_job.theater;
        job.time_start = new Date(new_job.time_start),
        job.time_end = new Date(new_job.time_end)
        saveMovie(movie, function(movie_id) {
        	job.movie = movie_id;
        	job.save(function(err, job) {
				Job.findById(job._id).populate('movie').exec(function(err, job) {
					res.json(job);
				});
			});
        })
    });
});

app.get('/api/jobs/:job_id', function(req, res) {
	Job.findById(req.params.job_id).populate('movie').exec(function(err, job) {
		if (err) throw err;
		res.json(job);
	});
});

app.post('/api/jobs/:job_id/toggle', function(req, res) {
	var job_id = req.params.job_id;
	Job.findById(job_id, function(err, job) {
		if (err) throw err;
		job.active = req.body.state ? req.body.state : !job.active;
		job.save(function(err) {
			if (err) throw err;
			res.json(job);
		})
	});
});

app.get('*', function(req, res) {
    res.sendfile('./public/index.html'); // load the single view file (angular will handle the page changes on the front-end)
});

app.listen(process.env.PORT || 8090);
console.log("App listening on port 8080");

//helper functions
function saveMovie(fandango_movie, callback) {
	Movie.findOne({fandango_id: fandango_movie.id}, function(err, movie) {
		if (err) throw err;
		if (!movie) {
			var movie = new Movie({
				name: fandango_movie.name,
				fandango_id: fandango_movie.id,
				fandango_slug: fandango_movie.slug,
	        });
		}
		movie.save(function(err, m) {
			callback(m._id);
		});
	})
}
@@ -662,16 +662,74 @@
 uery.q;%0A
+    var type = req.query.type ? req.query.type : 'Movie';%0A
 %09request
@@ -872,22 +872,24 @@
 %7B%0A%09%09var 
-movies
+response
  = %5B%5D;%0A%09
@@ -985,16 +985,112 @@
 Type ===
+ type) %7B%0A%09%09%09%09%09var obj = %7B%0A%09%09%09%09%09%09id: result.Id,%0A%09%09%09%09%09%09name: result.Name,%0A%09%09%09%09%09%7D%0A%09%09%09%09%09if (type ===
  'Movie'
@@ -1094,24 +1094,25 @@
 ie') %7B%0A%09%09%09%09%09
+%09
 var movie_sl
@@ -1129,16 +1129,17 @@
 t.Name;%0A
+%09
 %09%09%09%09%09mov
@@ -1174,16 +1174,17 @@
 Case();%0A
+%09
 %09%09%09%09%09mov
@@ -1231,24 +1231,25 @@
 , '');%0A%09%09%09%09%09
+%09
 movie_slug =
@@ -1293,103 +1293,66 @@
 1);%0A
-%0A
+%09
 %09%09%09%09%09
-movies.push(%7B%0A%09%09%09%09%09%09id: result.Id,%0A%09%09%09%09%09%09name: result.Name,%0A%09%09%09%09%09%09slug: movie_slug%0A%09%09%09%09%09%7D
+obj.slug = movie_slug;%0A%09%09%09%09%09%7D%0A%09%09%09%09%09response.push(obj
 );%0A%09
@@ -1379,14 +1379,16 @@
 son(
-movies
+response
 );%0A%09

Refactor search to filter by different types of search results, defaulting to movie