(function($){
    
    $(document).ready(function(){

        $(".select2-search__field, input[name=post_title]").keypress(function (e) {
            var keyCode = e.keyCode || e.which;

            //Regex for Valid Characters i.e. Alphabets and Numbers.
            var regex = /^[A-Za-z0-9\s\-\_]+$/;

            //Validate TextBox value against the Regex.
            var isValid = regex.test(String.fromCharCode(keyCode));
            if (!isValid) {
                alert("Only Alphabets and Numbers allowed.");
            }

            return isValid;
        });

        function paypopup() {
            $('.success').css('opacity','1');
            $('.success').css('z-index','99999');
            $('.success .poppup_box').css('transform','scale(1)');
            $('.success .poppup_box').css('opacity','1');
        }
       
        var getUrlParameter = function getUrlParameter(sParam) {
            var sPageURL = window.location.search.substring(1),
                sURLVariables = sPageURL.split('&'),
                sParameterName,
                i;
        
            for (i = 0; i < sURLVariables.length; i++) {
                sParameterName = sURLVariables[i].split('=');
        
                if (sParameterName[0] === sParam) {
                    return sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
                }
            }
            return false;
        };
        
        
        var old_url = getUrlParameter('url');
        var project = getUrlParameter('project');
        var prefix = getUrlParameter('prefix');
        var stripeForm;
        var NewprojectName;
        $('.range_inner').css('width','0%')
        
        
        $('#main_form').submit(function(e){
            e.preventDefault(); 

            window.onbeforeunload = function (e) {
                return "Please click 'Stay on this Page' if you did this unintentionally";
            };
               //var stripeForm = $(this).serialize();
            NewprojectName = $("input[name=post_title]").val();
            stripeForm = new FormData(this);
            $(this).find('button[type=submit]').append('<i class="fa fa-spinner fa-spin" style="font-size:24px"></i>');
            $(this).find('button[type=submit]').prop('disabled',true);
            // add_project("123")
            projectUnzip(this);
         
        });
        
    function add_project(new_url){
        // console.log(prefix);
        // return false;
        stripeForm.append('action','add_project');
        stripeForm.append('post_url',new_url);
        stripeForm.append('old_url',old_url);
        stripeForm.append('project_name',project);
        stripeForm.append('prefix',prefix);
        
        $.ajax({
           type: 'post',
           url: 'https://clone.onlinetestingserver.com/template_hub/wp-json/api/insert_post',
           data: stripeForm,
           dataType : 'json',
           cache:false,
           contentType: false,
           processData: false,
           success: function (response) {
            console.log(response);
            },
            error : function(errorThrown){
            console.log(errorThrown);
            }
        });
    }
        
        
 
        //  $('.continue').click(function(e){
        //     e.preventDefault(); 

        //     $(this).append('<i class="fa fa-spinner fa-spin" style="font-size:24px"></i>');
        //     $(this).prop('disabled',true);

        //     projectUnzip(this);
        // });


         function projectUnzip(e,useOldProject = true) {

            ststus_changer('start','project_unzip',10);
            $.ajax({
               type: 'post',
               url: 'https://clone.onlinetestingserver.com/ptp/inc/main.php',
               data: {action:'projectUnzip', project_name:project, useOldProject:useOldProject,new_project_name:NewprojectName},
               dataType : 'json',
               success: function (response) {
                console.log(response);
                    if(!response.status){
                         swal({
                              title: "Error!",
                              text: response.error,
                              icon: "warning",
                              button: "Close",
                            });
                         ststus_changer('error','project_unzip');
                         $('.fa-spinner').remove();
                    }
                    else{
                        if (response.auto_redirect) {window.location.href = response.redirect_url;}
                        else{ 

                            if (response.ifUseOldProject) { 
                                swal({
                                  title: "Backup is already exists!",
                                  // text: "Backup is already exists!",
                                  icon: "warning",
                                  buttons: true,
                                  buttons: ["Create new backup", "Use old backup"],
                                  dangerMode: true,
                                })
                                .then((willDelete) => {
                                  if (willDelete) {
                                    swal("Use old Backup");
                                  } else {
                                    swal("Create new Backup");
                                  }
                                });
                            }

                                ststus_changer('end','project_unzip');

                                createDtatbace(e,response.project_name);

                            // swal({
                            //       text: response.error,
                            //       icon: "success",
                            //       button: "Close",
                            //     }); 
                        }
                    } 
                },
                error : function(errorThrown){
                    ststus_changer('error','project_unzip');
                     $('.fa-spinner').remove();
                console.log(errorThrown);
                }
            });
         }

        function createDtatbace(e,project_name) {
            
            ststus_changer('start','create_db',30);
            ststus_changer('start','create_user',40);
            ststus_changer('start','generate_password',50);
            
            $.ajax({
               type: 'post',
               url: 'https://clone.onlinetestingserver.com/ptp/inc/main.php',
               data: {action:'createDtatbace', project_name:project_name},
               dataType : 'json',
               success: function (response) {
                console.log(response);
                    if(!response.status){
                        //$(thiss).append('<p class="eer" style="color:red;">'+response.error+'</p>');
                         swal({
                              title: "Error!",
                              text: response.error,
                              icon: "warning",
                              button: "Close",
                            });
                            ststus_changer('error','create_db');
                            ststus_changer('error','create_user');
                            ststus_changer('error','generate_password');
                            $('.fa-spinner').remove();
                    }
                    else{
                        if (response.auto_redirect) {window.location.href = response.redirect_url;}
                        else{ 
                            ststus_changer('end','create_db');
                            ststus_changer('end','create_user');
                            ststus_changer('end','generate_password');
                            $('.create_db').find('.status').html('Completed - - - - - <small> Database name </small> <a href="#" target="_blank"> '+ response.dbname +'</a>');
                            $('.create_user').find('.status').html('Completed - - - - - <small> Username </small> <a href="#" target="_blank"> '+ response.dbname +'</a>');
                            $('.generate_password').find('.status').html('Completed - - - - - <small> Generated Password </small> <a href="#" target="_blank"> '+ response.password +'</a>');
                            importDb(e,response.project_name,response.dbname,response.password);
                        // swal({
                        //       text: response.error,
                        //       icon: "success",
                        //       button: "Close",
                        //     }); 
                        }
                    } 
                },
                error : function(errorThrown){
                     ststus_changer('error','project_unzip');
                     $('.fa-spinner').remove();
                console.log(errorThrown);
                }
            });
         }



         function importDb(e,project_name,dbname,password) {
             ststus_changer('start','import_db',70);
            $.ajax({
               type: 'post',
               url: 'https://clone.onlinetestingserver.com/ptp/inc/main.php',
               data: {action:'importDb', project_name:project, new_project_name:project_name, dbname:dbname, password:password, prefix:prefix},
               dataType : 'json',
               success: function (response) {
                console.log(response);
                    if(!response.status){
                        //$(thiss).append('<p class="eer" style="color:red;">'+response.error+'</p>');
                         swal({
                              title: "Error!",
                              text: response.error,
                              icon: "warning",
                              button: "Close",
                            });
                             ststus_changer('error','project_unzip');
                            $('.fa-spinner').remove();
                    }
                    else{
                        if (response.auto_redirect) {window.location.href = response.redirect_url;}
                        else{ 
                             ststus_changer('end','import_db');
                             updateUrl(e,project_name,dbname,password)
                            // $('.continue').removeClass('continue').text('Done');
                            // $('.fa-spinner').remove();
                             
                        // swal({
                        //       text: response.error,
                        //       icon: "success",
                        //       button: "Close",
                        //     }); 
                        }
                    } 
                },
                error : function(errorThrown){
                console.log(errorThrown);
                 ststus_changer('end','import_db');
                 updateUrl(e,project_name,dbname,password)
                }
            });
         }
         
          function updateUrl(e,project_name,dbname,password) {
             ststus_changer('start','updateUrl',80);
            $.ajax({
               type: 'post',
               url: 'https://clone.onlinetestingserver.com/ptp/inc/main.php',
               data: {action:'updateUrl', project_name:project_name, dbname:dbname, password:password, old_url:old_url, prefix:prefix},
               dataType : 'json',
               success: function (response) {
                console.log(response);
                    if(!response.status){
                        //$(thiss).append('<p class="eer" style="color:red;">'+response.error+'</p>');
                         swal({
                              title: "Error!",
                              text: response.error,
                              icon: "warning",
                              button: "Close",
                            });
                    }
                    else{
                        if (response.auto_redirect) {window.location.href = response.redirect_url;}
                        else{


                            add_project(response.new_url);
                            ststus_changer('end','updateUrl');
                            ststus_changer('start','generate_link',100);
                            ststus_changer('end','generate_link');
                            $('.continue').removeClass('continue').text('Done');
                            $('.fa-spinner').remove();

                             
                        // swal({
                        //       text: response.error,
                        //       icon: "success",
                        //       button: "Close",
                        //     }); 
                            // html = `<table>
                            //           <tr><th>DataBase Name</th><td>`+ dbname +`</td></tr>
                            //           <tr><th>User Name</th><td>`+ dbname +`</td></tr>
                            //            <tr><th>Passwors</th><td>`+ password +`</td></tr>
                            //            <tr><th>Prefix</th> <td>`+ prefix +`</td></tr>
                            //            <tr><th>Project link</th><td><a href="`+ response.new_url +`" target="_blank">View This Project</a></td></tr>
                            //         </table>
                            //         <style>
                            //             table {font-family: arial, sans-serif;border-collapse: collapse;width: 100%;}
                            //             td, th {border: 1px solid #dddddd;text-align: left;padding: 8px;}
                            //             tr:nth-child(even) {background-color: #da96da3b;}
                            //             .swal-modal {width: auto !important;}
                            //         </style>`
                            html = `<a href="`+ response.new_url +`" target="_blank" class="theme_btn">View This Project</a>`
                            
                            $('.uplode_detail').html(html);
                            paypopup();

                            setTimeout(function () {
                                let newTab = window.open(response.new_url, '_blank', '');
                            }, 3000);
                                    
                            // setTimeout(
                            //   function() 
                            //   {
                            //     $('.swal-modal').find('.swal-text').html(html);
                            //   }, 500);
                            
                        }
                    } 
                },
                error : function(errorThrown){
                console.log(errorThrown);
                }
            });
         }
        
        
        
        var intervalId;
        function ststus_changer(type,target,percent=0) {
             clearInterval(intervalId);
             
            if(type == 'start')
            {
                $('.active_status').removeClass('active_status');
                $('.'+target).addClass('active_status');
                $('.range_inner').css('width',percent+'%')
            }
            else if(type == 'error'){
                    jQuery('.continue').text('ReSubmit');
                    jQuery('.continue').show();


                //  $('.'+target).find('.fa').removeClass('fa-sync').removeClass('fa-spin').addClass('fa-times');
                // $('.'+target).find('.status').text('error');
            }
            else
            {
                // clearInterval(intervalId);
                // $('.'+target).find('.fa').removeClass('fa-sync').removeClass('fa-spin').addClass('fa-check');
                // $('.'+target).find('.status').text('Completed');
                // $('.'+target).find('.percent').text('100%');
                // $('.'+target).find('.range_inner').css('width','100%')
            }
        }
        
        



});
})(jQuery);