/**
* File which deals with adding and removing downloads from
* the admin section of the website.
*
* @author Jeffery Russell 6-30-18
*/
//file IO
const utils = require('../../utils/utils.js');
//updates db
const sql = require('../../utils/sql');
//parses post data
const qs = require('querystring');
/**
* Processes post requests from the addDownload form
*
* @param postData
* @returns {*|Promise}
*/
const addDownloadPostData = function(postData)
{
return new Promise(function(resolve, reject)
{
const post = qs.parse(postData);
if(post.add_download)
{
sql.addDownload(post.add_download_name, post.add_download_file)
.then(function()
{
resolve("");
}).catch(function(error)
{
reject(error);
})
}
else
{
resolve("");
}
});
};
/**
* Displays the addDownload form the the user
*
* @param postData
* @returns {*|Promise}
*/
const addDownload = function(postData)
{
return new Promise(function(resolve, reject)
{
Promise.all([addDownloadPostData(postData),
utils.include("./admin/downloads/addDownload.html")]).then(function(html)
{
resolve("
" + html.join('') + "
");
}).catch(function(error)
{
reject(error);
})
});
};
/**
* Handel form requests from the downloads table
*
* @param postData
* @returns {*|Promise}
*/
const displayDownloadsPostData = function(postData)
{
return new Promise(function(resolve, reject)
{
const post = qs.parse(postData);
if(post.delete_download)
{
sql.removeDownload(post.delete_download).then(function()
{
resolve(postData);
}).catch(function(err)
{
reject(err);
});
}
else
{
resolve(postData);
}
});
};
/**
* Renders a single download row in the downloads table
*
* @param download
* @returns {*|Promise}
*/
const renderDownloadRow = function(download)
{
return "" +
"" + download.name + " | " +
"" + download.file + " | " +
"" + download.download_count + " | " +
" | " +
"
";
};
/**
* Displays all the download information in a table
* @param postData
* @returns {*|Promise}
*/
const displayDownloads = function(postData)
{
var html = "";
return new Promise(function(resolve, reject)
{
displayDownloadsPostData(postData).then(function()
{
html += "
" +
"
Downloads
" +
"
" +
"" +
"Download Name | File | " +
"Download Count | Delete | " +
"
";
sql.getAllDownloads().then(function(downloads)
{
var downloadPromises = [];
downloads.forEach(function(download)
{
downloadPromises.push(renderDownloadRow(download));
});
Promise.all(downloadPromises).then(function(htmls)
{
const htmlafter = "
" +
"
";
resolve(html + htmls.join('') + htmlafter);
});
}).catch(function(error)
{
reject(error);
});
});
});
};
module.exports=
{
/**
* Renders tha download section of the admin page
*
* @param postData
* @returns {Promise}
*/
main: function(postData)
{
return new Promise(function(resolve, reject)
{
Promise.all([addDownload(postData),
displayDownloads(postData)]).then(function(html)
{
resolve("" + html.join('') + "
");
}).catch(function(error)
{
console.log("error in add downloads.js");
reject(error);
});
});
}
};