
if (api_base_url === undefined){
    var api_base_url = ""
}

$.fn.crud = function(type, url, data, log=true) {

    var self = $(this)

    self.attr("disabled", true)

    var doing = type+" "+url
    var done = "btn-outline-success"
    var fail = "btn-outline-danger"
    var delay = 800

    const ref_time = new Date().getTime()/1000
    
    return $.ajax({
        url: api_base_url+url,
        type: type,
        // crossDomain: true,
        dataType: 'json',
        data: JSON.stringify(data),
        contentType: "application/json",
    })
        .done(function(e){
            console.log("OK "+doing)

            self.addClass(done)
            setTimeout(function () {
                self.removeClass(done)
            }, delay);

        })
        .fail(function(e, status, error){
            console.log("NOT OK "+doing)
            console.log(status)
            console.log(error)

            self.addClass(fail)
            setTimeout(function () {
                self.removeClass(fail)
            }, delay);

        })
        .always(function(e){
            console.log("FINISHED "+doing)
            //console.log("Server: "+api_base_url)
            console.log("Sent: "+ JSON.stringify(data))
            var res = log ? JSON.stringify(e) : "a long json"
            console.log("Received: " + res)
            console.log("After: " + difftime(ref_time))
            self.attr("disabled", false)
        })

} // crud

function serializeObject(selector){
    var raw_form_data = $(selector).serializeArray();
    var data = {}
    $.each(raw_form_data, function() {
	data[this.name] = this.value;
    });
    return data;
}

function difftime(unix_timestamp){
    let now = new Date().getTime() / 1000
    var diff = now - unix_timestamp
    return diff.toFixed(3)
}

// var client_unix_time;

// function client_clock(){
//     client_unix_time = new Date().getTime()/1000.0
//     // console.log(client_unix_time)
// }

// setInterval(client_clock, 100);
// client_clock()
