import { Framework } from "core";

((f) => {
	f.ajax = class{
		#xhr = null;
		#default_args = {
			"url": "",
			"type": "get",
			"data": {},
			"success": null,
			"error": null
		};
		#url = "";
		#type = "";
		#data = {};
		#callbacks=[];
		constructor(args) {
			this.#xhr = new XMLHttpRequest();
		}
		done(callback){
			if(typeof callback === "function"){
				this.#callbacks.push({"callback_success":callback});
			}
			return this;
		}
		success(callback){
			return this.done(callback);
		}
		fail(callback){
			if(typeof callback === "function"){
				this.#callbacks.push({"callback_error":callback});
			}
			return this;
		}
		error(callback){
			return this.fail(callback);
		}
		always(callback){
			if(typeof callback === "function"){
				this.#callbacks.push({"callback_complete":callback});
			}
			return this;
		}
		complete(callback){
			return this.always(callback);
		}
		progress(callback){
			if(typeof callback === "function"){
				this.#callbacks.push({"callback_progress":callback});
			}
			return this;
		}
		then(successCallback,errorCallback=null){
			if(typeof callback_success === "function"){
				if(typeof errorCallback === "function"){
					this.#callbacks.push({"callback_success":successCallback, "callback_error": errorCallback});
				}else{
					this.#callbacks.push({"callback_success":callback_success});
				}
			}
			return this;
		}
		abort(){
			this.#xhr.abort();
			return this;
		}
		#load(){
			this.#xhr.onerror = (error) => {
				this.#callbacks.forEach((data)=>{
					if(data.callback_error !== undefined){
						data.callback_error(this.#xhr, this.#xhr.statusText,error);
					}
				});
				this.#callbacks.forEach((data)=>{
					if(data.callback_complete !== undefined){
						data.callback_complete(this.#xhr, this.#xhr.statusText,error);
					}
				});
			};
			this.#xhr.addEventListener("progress", (evt) => {
				this.#callbacks.forEach((data)=>{
					if(data.callback_progress !== undefined){
						data.callback_progress(evt, this.#xhr);
					}
				});
			});
		}
	};
	f.ajax=function(args) {
		/*
			jqXHR.done(function( data, textStatus, jqXHR ){});

			jqXHR.fail(function( jqXHR, textStatus, errorThrown ){});
			
			jqXHR.always(function( data|jqXHR, textStatus, jqXHR|errorThrown){});

			jqXHR.then(function( data, textStatus, jqXHR ) {}, function( jqXHR, textStatus, errorThrown ){});
.
		 */
        xhttp.onload = function() {
            let response;
            if (this.readyState == 4 && this.status == 200) {
                let response="";
                try {
                //check if the response in json 
                //if json the parse it
                    response=JSON.parse(this.responseText)
                } catch (e) {
                //if not json the simple reurn the response
                    response = this.responseText;
                }
                 // give a success callback
                return success(response);
            } else {
            //give a fail callback with the error status 
                return fail(this.status);
            }
        };
        let parameters="";
        if (args) {
            type = args["type"];
            if ('data' in args) {
            //converting object to url URLSearchParams
                parameters = new URLSearchParams(args['data']).toString();
            }
        }
        if (type && type.toUpperCase()=='POST') {
            xhttp.open("POST", url, true);
            xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            xhttp.send(parameters);
        } else if (!type || type.toUpperCase()=='GET'){
            xhttp.open("GET", url + "?" + parameters, true);
            xhttp.setRequestHeader("X-Requested-With", "XMLHttpRequest");
            xhttp.send();
        }
    }
})(Framework);