/**
 * Hasium Theme Admin Settings
 *
 *
 * @since 1.2.4
 */

(function($){

	HasiumThemeAdmin = {

		init: function()
		{
			this._bind();
		},


		/**
		 * Binds events for the Hasium Theme.
		 *
		 * @since 1.0.0
		 * @access private
		 * @method _bind
		 */
		_bind: function()
		{
			$( document ).on('ast-after-plugin-active', HasiumThemeAdmin._disableActivcationNotice );
			$( document ).on('click' , '.hasium-install-recommended-plugin', HasiumThemeAdmin._installNow );
			$( document ).on('click' , '.hasium-activate-recommended-plugin', HasiumThemeAdmin._activatePlugin);
			$( document ).on('click' , '.hasium-deactivate-recommended-plugin', HasiumThemeAdmin._deactivatePlugin);
			$( document ).on('wp-plugin-install-success' , HasiumThemeAdmin._activatePlugin);
			$( document ).on('wp-plugin-install-error'   , HasiumThemeAdmin._installError);
			$( document ).on('wp-plugin-installing'      , HasiumThemeAdmin._pluginInstalling);
			$( document ).on('click', '.robot-wizard-permissions', HasiumThemeAdmin._showPermission );
			$( document ).on('click', '.robot-wizard-opt-in', HasiumThemeAdmin._optIn );
            $( document ).on('click', '.robot-wizard-skip', HasiumThemeAdmin._skip );

		},

		/**
         * Opt-in
         *
         */
		 _optIn: function( event ) {

            event.preventDefault();

            console.log('click opt in');

            $.ajax({
                    url  : hasium.ajaxUrl,
                    type : 'POST',
                    dataType: 'json',
                    data : {
                        action       : 'hasium_save_user_data',
                        type         : 'opt-in',
                    },
                    beforeSend: function() {
                    },
                })
                .fail(function( jqXHR ){
                    console.log( jqXHR.status + ' ' + jqXHR.responseText);
                    window.location.href = "admin.php?page=hasium-admin-menu";
                })
                .done(function ( option ) {
                    if( false === option.success ) {
                        console.log(option);
                    } else {
                        console.log(option);
                        window.location.href = "admin.php?page=hasium-admin-menu";
                    }

                });

        },

        /**
         * Skip opt in
         *
         */
        _skip: function( event ) {

            event.preventDefault();

            console.log('click skip.');

            $.ajax({
                url  : hasium.ajaxUrl,
                type : 'POST',
                dataType: 'json',
                data : {
                    action       : 'hasium_save_user_data',
                    type         : 'skip',
                },
                beforeSend: function() {
                },
            })
            .fail(function( jqXHR ){
                console.log( jqXHR.status + ' ' + jqXHR.responseText);
            })
            .done(function ( option ) {
                if( false === option.success ) {
                    console.log(option);
                } else {
                    console.log(option);
                    window.location.href = "admin.php?page=hasium-admin-menu";
                }

            });

        },

		/**
         * Show permission details
         *
         */
		 _showPermission: function( event ) {

            event.preventDefault();

            if ($("#robot_wizard_set_up").hasClass("wizard-set-up")){
				$("#robot_wizard_set_up").css("display", "none");
				$("#robot_wizard_set_up").removeClass("wizard-set-up");
			}else{
				$("#robot_wizard_set_up").css("display", "block");
				$("#robot_wizard_set_up").addClass("wizard-set-up");
			}
        },

		/**
		 * Plugin Installation Error.
		 */
		_installError: function( event, response ) {

			var $card = jQuery( '.hasium-install-recommended-plugin' );

			$card
				.removeClass( 'button-primary' )
				.addClass( 'disabled' )
				.html( wp.updates.l10n.installFailedShort );
		},

		/**
		 * Installing Plugin
		 */
		_pluginInstalling: function(event, args) {
			event.preventDefault();

			var slug = args.slug;

			var $card = jQuery( '.hasium-install-recommended-plugin' );
			var activatingText = hasium.recommendedPluiginActivatingText;

			$card.each(function( index, element ) {
				element = jQuery( element );
				if ( element.data('slug') === slug ) {
					element.addClass('updating-message');
					element.html( activatingText );
				}
			});

		},

		/**
		 * Activate Success
		 */
		_activatePlugin: function( event, response ) {

			event.preventDefault();

			var $message = jQuery(event.target);
			var $init = $message.data('init');
			var activatedSlug;

			if (typeof $init === 'undefined') {
				var $message = jQuery('.hasium-install-recommended-plugin[data-slug=' + response.slug + ']');
				activatedSlug = response.slug;
			} else {
				activatedSlug = $init;
			}

			// Transform the 'Install' button into an 'Activate' button.
			var $init = $message.data('init');
			var activatingText = hasium.recommendedPluiginActivatingText;
			var settingsLink = $message.data('settings-link');
			var settingsLinkText = hasium.recommendedPluiginSettingsText;
			var deactivateText = hasium.recommendedPluiginDeactivateText;
			var hasiumSitesLink = hasium.hasiumSitesLink;

			$message.removeClass( 'install-now installed button-disabled updated-message' )
				.addClass('updating-message')
				.html( activatingText );

			// WordPress adds "Activate" button after waiting for 1000ms. So we will run our activation after that.
			setTimeout( function() {

				$.ajax({
					url: hasium.ajaxUrl,
					type: 'POST',
					data: {
						'action'            : 'hasium-sites-plugin-activate',
						'init'              : $init,
					},
				})
				.done(function (result) {

					if( result.success ) {
						var output  = '<a href="#" class="hasium-deactivate-recommended-plugin" data-init="'+ $init +'" data-settings-link="'+ settingsLink +'" data-settings-link-text="'+ deactivateText +'" aria-label="'+ deactivateText +'">'+ deactivateText +'</a>';
							output += ( typeof settingsLink === 'string' && settingsLink != 'undefined' ) ? '<a href="' + settingsLink +'" aria-label="'+ settingsLinkText +'">' + settingsLinkText +' </a>' : '';
							output += ( typeof settingsLink === undefined && settingsLink != undefined ) ? '<a href="' + settingsLink +'" aria-label="'+ settingsLinkText +'">' + settingsLinkText +' </a>' : '';

						$message.removeClass( 'hasium-activate-recommended-plugin hasium-install-recommended-plugin button button-primary install-now activate-now updating-message' );

						$message.parent('.ast-addon-link-wrapper').parent('.hasium-recommended-plugin').addClass('active');
						$message.parents('.ast-addon-link-wrapper').html( output );

						jQuery(document).trigger( 'ast-after-plugin-active', [hasiumSitesLink, activatedSlug] );

					} else {

						$message.removeClass( 'updating-message' );

					}

				});

			}, 1200 );

		},

		/**
		 * Activate Success
		 */
		_deactivatePlugin: function( event, response ) {

			event.preventDefault();

			var $message = jQuery(event.target);

			var $init = $message.data('init');

			if (typeof $init === 'undefined') {
				var $message = jQuery('.hasium-install-recommended-plugin[data-slug=' + response.slug + ']');
			}

			// Transform the 'Install' button into an 'Activate' button.
			var $init = $message.data('init');
			var deactivatingText = $message.data('deactivating-text') || hasium.recommendedPluiginDeactivatingText;
			var settingsLink = $message.data('settings-link');
			var settingsLinkText = hasium.recommendedPluiginSettingsText;
			var activateText = hasium.recommendedPluiginActivateText;

			$message.removeClass( 'install-now installed button-disabled updated-message' )
				.addClass('updating-message')
				.html( deactivatingText );

			// WordPress adds "Activate" button after waiting for 1000ms. So we will run our activation after that.
			setTimeout( function() {

				$.ajax({
					url: hasium.ajaxUrl,
					type: 'POST',
					data: {
						'action'            : 'hasium-sites-plugin-deactivate',
						'init'              : $init,
					},
				})
				.done(function (result) {

					if( result.success ) {
						var output = '<a href="#" class="hasium-activate-recommended-plugin" data-init="'+ $init +'" data-settings-link="'+ settingsLink +'" data-settings-link-text="'+ activateText +'" aria-label="'+ activateText +'">'+ activateText +'</a>';
						$message.removeClass( 'hasium-activate-recommended-plugin hasium-install-recommended-plugin button button-primary install-now activate-now updating-message' );

						$message.parent('.ast-addon-link-wrapper').parent('.hasium-recommended-plugin').removeClass('active');

						$message.parents('.ast-addon-link-wrapper').html( output );

					} else {

						$message.removeClass( 'updating-message' );

					}

				});

			}, 1200 );

		},

		/**
		 * Install Now
		 */
		_installNow: function(event)
		{
			event.preventDefault();

			var $button 	= jQuery( event.target ),
				$document   = jQuery(document);

			if ( $button.hasClass( 'updating-message' ) || $button.hasClass( 'button-disabled' ) ) {
				return;
			}

			if ( wp.updates.shouldRequestFilesystemCredentials && ! wp.updates.ajaxLocked ) {
				wp.updates.requestFilesystemCredentials( event );

				$document.on( 'credential-modal-cancel', function() {
					var $message = $( '.hasium-install-recommended-plugin.updating-message' );

					$message
						.addClass('hasium-activate-recommended-plugin')
						.removeClass( 'updating-message hasium-install-recommended-plugin' )
						.text( wp.updates.l10n.installNow );

					wp.a11y.speak( wp.updates.l10n.updateCancel, 'polite' );
				} );
			}

			wp.updates.installPlugin( {
				slug:    $button.data( 'slug' )
			});
		},


		/**
		 * After plugin active redirect and deactivate activation notice
		 */
		_disableActivcationNotice: function( event, hasiumSitesLink, activatedSlug )
		{
			event.preventDefault();

			if ( activatedSlug.indexOf( 'wphobby-demo-import' ) >= 0 ) {
				window.location.href = hasiumSitesLink;
			}

		},

	};

	/**
	 * Initialize HasiumThemeAdmin
	 */
	$(function(){
		HasiumThemeAdmin.init();
	});

})(jQuery);