/* jshint browser: true */
/* global BP_Nouveau, plupload, CommunityAllyLoader */
/* @since 3.0.0 */
/* @version 8.0.0 */
window.bp = window.bp || {};

( function( bp, $ ) {
	// Bail if not set
	if ( typeof BP_Nouveau === 'undefined' ) {
		return;
	}

	bp.Nouveau = bp.Nouveau || {};

	// <editor-fold defaultstate="collapsed" desc="Copy Discussion shortcode">
	var $hidden_copy_element = false;
	function copy_text_to_clipboard($parent_element, text_to_copy) {
		var current_focus_element = document.activeElement,
			is_success = false;
		if (!$hidden_copy_element) {
			$hidden_copy_element = $('<textarea style="position:absolute;top:0;left:-99999px;width:0;height:0"></textarea>');
		}
		$hidden_copy_element.show();
		$parent_element.append($hidden_copy_element);

		$hidden_copy_element.val(text_to_copy);

		// select the hidden element content
		$hidden_copy_element[0].focus();
		$hidden_copy_element[0].setSelectionRange(0, text_to_copy.length);

		// copy the selection
		try {
			is_success = document.execCommand("copy");
		} catch(e) {
		}
		// restore original focus
		if (current_focus_element && typeof current_focus_element.focus === "function") {
			current_focus_element.focus();
		}

		$hidden_copy_element.val('').hide();
		return is_success;
	}
	$(document).on('click touchend', '[communityally-discussion-shortcode-copy-button]', function() {
		var $this = $(this),
			$parent = $this.parents('.communityally-discussion-entry-shortcode'),
			group_id = $this.attr('communityally-discussion-shortcode-copy-button'),
			val = '[communityally_group group_id="' + group_id + '"]';
		if (copy_text_to_clipboard($parent, val)) {
			$parent.find('.communityally-discussion-shortcode-copy-success').show();
			setTimeout(function() {
				$parent.find('.communityally-discussion-shortcode-copy-success').hide();
			}, 2000);
		} else {
			let $error_elem = $parent.find('.communityally-discussion-shortcode-copy-fail');
			$error_elem.find('.communityally-shortcode-copy-fail-text').text(val);
			$error_elem.show();
		}
	});
	// </editor-fold>
	bp.Nouveau.Discussion = {

		start: function () {
			this.addListeners();
		},

		addListeners: function () {
			// create new group
			$(document).on('click touchend', '[communityally-discussion-add-group-button]', this.showAddGroupModal);
			$(document).on('click touchend', '.communityally-modal-close', function () {
				let target_modal_to_close = $(this).attr('communityally-modal-close');
				$( '#' + target_modal_to_close ).hide();
			});
			$(document).on('click touchend', '[communityally-add-child-group-submit]', this.addChildGroupAjax);
			$(document).on('click touchend', '[communityally-edit-discussion-id]', this.showEditDiscussionModal);
			$(document).on('click touchend', '[communityally-discussion-edit-modal-submit]', this.editDiscussionAjax);
			$(document).on('click touchend', '[communityally-delete-discussion-id]', this.deleteDiscussion);
		},

		showEditDiscussionModal: function () {
			let group_id = $(this).attr('communityally-edit-discussion-id');
			$('#communityally-edit-child-group-modal-' + group_id).show();
		},
		editDiscussionAjax: function () {
			let $this = $(this),
				edit_attr = $this.attr('communityally-discussion-edit-modal-submit'),
				parts = edit_attr.split('|'),
				$modal = $this.parents('[communityally-edit-child-group-modal]'),
				details = communityally_serialize_value_in_container($modal),
				data = {
					action: 'communityally_groups_edit_child_group',
					details: JSON.stringify(details),
					nonce: CommunityAllyLoader.nonce
				};
			if (parts.length < 2) {
				return false;
			}
			data['group_id'] = parts[0];

			let parent_group_id = parts[1];
			data['parent_id'] = parent_group_id;

			$('#communityally-wait-overlay').show();

			$.ajax({
				type: 'POST',
				url: CommunityAllyLoader.ajax_url,
				data: data,
				success: function(response) {
					try {
						var result = JSON.parse(response);
						if ('status' in result) {
							if ('success' === result['status']) {
								$('[communityally-discussion-content-topics-container="' + parent_group_id + '"]').html(result['code']);
							} else {
								throw result['message'];
							}
						}
					} catch (e) {
						console.log(e);
					}
					$('#communityally-wait-overlay').hide();
				}
			});
			return false;
		},
		deleteDiscussion: function () {
			let $this = $(this),
				delete_attr = $this.attr('communityally-delete-discussion-id'),
				parts = delete_attr.split('|'),
				data = {
					action: 'communityally_groups_delete_child_group',
					nonce: CommunityAllyLoader.nonce
				},
				conf = confirm(CommunityAllyLoader.messages.DELETE_DISCUSSION_WARNING);
			if (conf !== true) {
				return false;
			}
			if (parts.length < 2) {
				return false;
			}
			data['group_id'] = parts[0];

			let parent_group_id = parts[1];
			data['parent_id'] = parent_group_id;

			$('#communityally-wait-overlay').show();
			$.ajax({
				type: 'POST',
				url: CommunityAllyLoader.ajax_url,
				data: data,
				success: function(response) {
					try {
						var result = JSON.parse(response);
						if ('status' in result) {
							if ('success' === result['status']) {
								$('[communityally-discussion-content-topics-container="' + parent_group_id + '"]').html(result['code']);
							} else {
								throw result['message'];
							}
						}
					} catch (e) {
						console.log(e);
					}
					$('#communityally-wait-overlay').hide();
				}
			});
			return false;
		},
		/**
		 *  make add child-group modal visible
		 * */
		showAddGroupModal: function () {
			let group_id = $(this).attr('communityally-discussion-add-group-button');
			$('[communityally-add-child-group-modal="' + group_id + '"]').show();
		},

		/**
		 * gather information and send request to create group
		 * */
		addChildGroupAjax: function () {
			let $this = $(this),
				group_id = $(this).attr('communityally-add-child-group-submit'),
				$modal = $this.parents('[communityally-add-child-group-modal]'),
				details = communityally_serialize_value_in_container($modal),
				data = {
					action: 'communityally_groups_add_child_group',
					group_id: group_id,
					details: JSON.stringify(details),
					nonce: CommunityAllyLoader.nonce
				};

			$('#communityally-wait-overlay').show();
			$.ajax({
				type: 'POST',
				url: CommunityAllyLoader.ajax_url,
				data: data,
				success: function(response) {
					try {
						var result = JSON.parse(response);
						if ('status' in result) {
							if ('success' === result['status']) {
								$('[communityally-discussion-content-topics-container="' + group_id + '"]').html(result['code']);
								// clear form after successful submission
								$modal.find('[communityally-param]').val('').change();
							} else {
								throw result['message'];
							}
						}
					} catch (e) {
						console.log(e);
					}
					$modal.hide();
					$('#communityally-wait-overlay').hide();
				}
			});
		}
	};

	bp.Nouveau.Discussion.start();

})(window.bp, jQuery);