$(document).ready(function(){

    $('#tblToken').on('click', function(e){
        
        e.preventDefault();

        if(isWebsiteNameExist()){
            //$("#tokenModal").hide();
            alert("Nama website sudah terpakai");
            //$("#tokenModal").hide();
        }else if(isDomainExist()){
            alert("Domain sudah terpakai");
        }else if(!checkDomain()){
            alert("Domain Offline");
        }else{
            generateToken();
            //alert("mashook")
        }
    })

    function redirected(){
        window.location.href = "lihattoken";
    }
    //is domain online
    // checkServer('https://www.facebook.com/', 5000);
    // function checkServer(url, timeout) {
    //     const controller = new AbortController();
    //     const signal = controller.signal;
    //     const options = { mode: 'no-cors', signal };
    //     const isOnline = true;
        
    //     return fetch(url, options)
    //       .then(setTimeout(() => { controller.abort() }, timeout))
    //       .then(response => console.log(url+' : online'))
    //       .catch(error => console.error(url+' : offline', error.message));
    //   }

    //checkDomain();
    function checkDomain(){
        let $webDomain   = $('#website_domain').val();
        let exist       = false;

        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: baseURL + '/api/checkDomain',
            async: false,
            data: {
                domain  : $webDomain,
            },
            success: function(result){
                console.log("success dom");
                //console.log(result.data);
                exist   = result.data;
            },
            error: function(){
                console.log("error");
            }
        });
        console.log($webDomain);
        console.log(exist);
        return exist;
    }

    isDomainExist();
    function isDomainExist(){
        let $websiteName    = $('#website_domain').val();
        let exist           = false;
        
        //console.log('fungsi domain exist');
        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: baseURL + '/api/websitelist',
            async: false,
            data: {
                id_user         : null
            },
            success: function(result){
                //console.log(result.data);
                let data = result.data;

                for(webDom in data){
                    if($websiteName === data[webDom].website_domain){
                        exist = true;
                    }
                }
            },
            error: function(xhr){
                alert(xhr.status+'-'+xhr.statusText);
            }
        });
        //console.log(exist);
        return exist;
    }

    //isWebsiteNameExist();
    function isWebsiteNameExist(){
        let $websiteName    = $('#website_name').val();
        let exist           = false;
        

       // console.log('fungsi masuk gan');
        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: baseURL + '/api/websitelist',
            async: false,
            data: {
                id_user         : null
            },
            success: function(result){
                //console.log(result.data);
                let data = result.data;

                for(webName in data){
                    if($websiteName === data[webName].website_name){
                        exist = true;
                    }
                }
                // var $select = $("#selectWeb option:selected").text();
                // console.log($select);
                
            },
            error: function(xhr){
                alert(xhr.status+'-'+xhr.statusText);
            }
        });
        return exist;
    }

    function generateToken(){
        let $websiteName    = $('#website_name').val();
        let $websiteDomain  = $('#website_domain').val();
        let $averageAge     = $('#average_age').val();
        let $token          = $('#tokenweb').val();
        let $id_user        = $('#id_user').val();
        let $post           = false;

        if($websiteName == null || $websiteName ==""){
            alert("nama website kosong");
            //$post = false;
            return false
        }else if($websiteDomain == null || $websiteDomain==""){
            alert("domain kosong");
            return false
        } else if($averageAge == null || $averageAge==""){
            alert("age kosong");
            return false
        }
        
        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: baseURL + '/api/generatetoken',
            //async: false,
            data: {
                website_name    : $websiteName,
                website_domain  : $websiteDomain,
                average_age_visitor : $averageAge,
                token           : $token,
                id_user         : $id_user
            },
            success: function(result){
                //console.log("success");
                //callback(location);
                redirected();
            },
            error: function(xhr){
                //alert(xhr.status+'-'+xhr.statusText);
            }
        });

        
    }

    isMaxWebsite(iduser)
    function isMaxWebsite(id){
        console.log(id)
    }

    // function isSiteOnline(url,callback) {
    //     // try to load favicon
    //     var timer = setTimeout(function(){
    //         // timeout after 5 seconds
    //         callback(false);
    //     },5000)
    
    //     var img = document.createElement("img");
    //     img.onload = function() {
    //         clearTimeout(timer);
    //         callback(true);
    //     }
    
    //     img.onerror = function() {
    //         clearTimeout(timer);
    //         callback(false);
    //     }
    
    //     img.src = url+"/favicon.ico";
    // }

    // isSiteOnline("http://www.facebook.com",function(found){
    // var isOnline = false;
    // if(found) {
    //     isOnline =  true;
    // }
    // else {
    //     isOnline = false;
    // }
    // console.log(isOnline);
    // return isOnline;
    // })


    // function CopyToClipboard() {
    //     if (document.selection) {
    //         var range = document.body.createTextRange();
    //         range.moveToElementText(document.getElementById("token"));
    //         range.select().createTextRange();
    //         document.execCommand("copy");
    //     } else if (window.getSelection) {
    //         var range = document.createRange();
    //         range.selectNode(document.getElementById("token"));
    //         window.getSelection().addRange(range);
    //         document.execCommand("copy");
    //     }

    // }


    // $(function () {
    //     $('[data-toggle="tooltip"]').tooltip()
    // })

});
