﻿/*
 * Example Huddle API Application
 *
 * This file contains example code for creating a file-manager style
 * application using the Huddle API. It makes use of the jQuery javascript
 * frameworks.
 *
 * @author Nick Skelton
 * @email nick@huddle.net
 * @copyright Huddle
 */

/*
 * Initialise the File Ferret when the DOM is ready
 */
$(document).ready(function() {
	fileFerret.init();
});

/*
 * File Ferret Code
 * Note, for this application, we're using a singleton design pattern
 */
fileFerret = {

	init : function() {
		this.getWorkspaces();
	},

	showLoader : function() {
		$('#loader').fadeIn('fast');
	},

	hideLoader : function() {
		$('#loader').fadeOut();
	},

	/*
	 * Display a feedback on API call errors
	 * Include a custom feedback message with the msg argument
	 */
	notifyError : function(msg) {
		if (!msg) {
			var msg = 'Unfortunately there was an error making the API call...';
		}
		$('#files').append('<p class="error">' + msg + '</p>');
		if ($('#files').is(':hidden')) {
			$('#files').show();
		}
	},

	/*
	 * API Call - return a list of workspaces
	 */
	getWorkspaces : function() {
		// Before we start the request we should show the loading feedback
		this.showLoader();
		$.ajax({
			url : 'proxy.php?path=/workspaces',
			type : 'GET',
			dataType : 'json',
			error : function() { fileFerret.notifyError('Username and password required') },
			success : function(response) {
				if (response.Success === false) {
					fileFerret.notifyError(response.Error.Msg);
				} else {
					fileFerret.showWorkspaceSelector(response.Data);
				}
			},
			complete : function() { fileFerret.hideLoader() }
		});
	},

	/*
	 * API Call - return a list of the top level files and folders of a workspace
	 * Requires a workspace ID (e.g. from getWorkspaces())
	 */
	getRootItems : function(workspace) {
		this.showLoader();
		$.ajax({
			url : 'proxy.php?path=/workspaces/' + workspace + '/items',
			type : 'GET',
			dataType : 'json',
			error : function() { fileFerret.notifyError() },
			success : function(response) {
				if (response.Success === false) {
					fileFerret.notifyError(response.Error.Msg);
				} else {
					fileFerret.showRootItems(response.Data);
				}
			},
			complete : function() { fileFerret.hideLoader() }
		});
	},

	/*
	 * API Call - return a list of the child files and folders of a folder
	 * Requires a folder ID (e.g. from getRootItems() or getChildItems())
	 */
	getChildItems : function(folder) {
		this.showLoader();
		$.ajax({
			url : 'proxy.php?path=/folders/' + folder + '/items',
			type : 'GET',
			dataType : 'json',
			error : function() { fileFerret.notifyError() },
			success : function(response) {
				if (response.Success === false) {
					fileFerret.notifyError(response.Error.Msg);
				} else {
					fileFerret.showChildItems(response.Data, folder);
				}
			},
			complete : function() { fileFerret.hideLoader() }
		});
	},

	/*
	 * API Call - Make an ajax request to return details of a single file
	 * using a file ID obtained from a getRootItems() or getChildItems() call
	 */
	getFileDetails : function(file) {
		this.showLoader();
		$.ajax({
			url : 'proxy.php?path=/files/' + file,
			type : 'GET',
			dataType : 'json',
			error : function() { fileFerret.notifyError() },
			success : function(response) {
				if (response.Success === false) {
					fileFerret.notifyError(response.Error.Msg);
				} else {
					fileFerret.showFileDetails(response.Data);
				}
			},
			complete : function() { fileFerret.hideLoader() }
		});
	},

	/*
	 * Append a new set of files and folders to a parent element
	 * e.g. when clicking on a folder, we append the data returned from getChildItems()
	 */
	addChild : function(data, parent) {
		var item = $('<li class="' + data.Type.toLowerCase() + '" rel="' + data.Id + '"></li>');
		var toggler  = $('<span class="title">' + data.Title + '</span>');
		toggler.appendTo(item);

		switch (data.Type.toLowerCase()) {
			case 'folder':
				// Allow folders to be collapsed/expanded
				toggler.click(function(e) {
					e.stopPropagation();
					var children = item.children('ul');

					// If we've already got the data before, then collapse
					// or expand the folder node, else make the API call
					// to return the child items data
					if (children.length > 0) {
						if (children.is(':visible')) {
							item.removeClass('selected');
							children.hide('fast');
						} else {
							item.addClass('selected');
							children.show('fast');
						}
					} else {
						$('#files li.selected').removeClass('selected');
						item.addClass('selected');
						fileFerret.getChildItems(data.Id);
					}
				});
			break;

			case 'file':
				// Make an API call to get the file details when
				// clicking on a file node
				toggler.click(function(e) {
					e.stopPropagation();
					fileFerret.getFileDetails(data.Id);
				});
			break;

		}
		item.appendTo(parent);
	},

	/*
	 * Take the response from getWorkspaces() and insert the list
	 * into a <select></select> box
	 */
	showWorkspaceSelector : function(response) {
		var selector = $('<select id="selector"><option>Choose a workspace to ferret!...</option></select>');

		jQuery.each(response, function(i, val) {
			var option = $('<option value="' + val.Id + '">' + val.Title + '</option>')
            option.appendTo(selector);
		});

		// Attach an event to the select box to request new root items via the
		// API when the workspace is changed
		selector.change(function() {
			if ($('#file-details').is(':visible')) {
				$('#file-details').fadeOut('slow');
			}

			var id = parseInt($(this).val());
			if (id > 0) {
				fileFerret.getRootItems($(this).val());
			} else {
				$('#file-list').empty();
				$('#files').append('<p class="error">There\'s nothing to find here!</p>');
			}
		});

		selector.wrap('<p></p>').appendTo($('#workspaces'));

	},

	/*
	 * Take the response from getRootItems() and add it to the page
	 * as an unordered list
	 */
	showRootItems : function(response) {
		if ($('#file-list').length > 0) {
			$('#file-list').fadeOut('fast').remove();
			$('#files').empty();
		}

		var list = $('<ul id="file-list" class="file-list"></ul>');

		jQuery.each(response, function(i, val) {
			fileFerret.addChild(val, list);
		});

		$('#files').append($('<h2>Here\'s what I found...</h2>')).append(list).fadeIn('fast');

	},

	/*
	 * Take the response from getChildItems() and display the items. We append new
	 * lists of files/folders to the relevant folder node using the addChild() function
	 * Requires a folder ID to which we're appending these items
	 */
	showChildItems : function(response, folder) {
		if (response.length > 0) {
			var list = $('<ul></ul>');
			jQuery.each(response, function(i, val) {
				fileFerret.addChild(val, list);
			});

			list.hide().appendTo($('li[rel="' + folder + '"]')).show('fast');
		} else {
			if ($('li[rel="' + folder + '"]').children('span.empty').length == 0) {
				$('<span class="empty">(This folder is empty)</span>').hide().appendTo($('li[rel="' + folder + '"]')).show('fast');
			}
		}

	},

	/*
	 * Takes the response from getFileDetails() and display a list of file
	 * details on the page
	 */
	showFileDetails : function(response) {
		var title = $('<h3>Details for file "' + response.Title + '"</h3>');
		var list = $('<ul></ul>');

		if (response.description) {
			var details = '<li>Description: ' + response.Description + '</li>';
		} else {
			var details = '';
		}
		details += '<li>Created by <strong>'
		details += response.CreatedByUserDisplayName
		details += '</strong> on ';
		details +=  response.Created.Day + '/';
		details +=  response.Created.Month + '/';
		details +=  response.Created.Year + ' ';
		details +=  response.Created.Hour + ':';
		details +=  response.Created.Minute;
		details += '</li>'

		details += '<li>Last Updated on ';
		details +=  response.LastUpdated.Day + '/';
		details +=  response.LastUpdated.Month + '/';
		details +=  response.LastUpdated.Year + ' ';
		details +=  response.LastUpdated.Hour + ':';
		details +=  response.LastUpdated.Minute;
		details += ' by <strong>' + response.LastEditedByUserDisplayName + '</strong></li>';

		details += '<li>Size: ' + response.Size + 'B</li>';
		details += '<li class="download-link"><a href="' + 'https://my.huddle.net/' + response.Url + '">Download this File...</a></li>';
		$(details).appendTo(list);

		$('#file-details').empty().append(title).append(list).fadeIn('fast');
	}
};