/**
 * Componenta de lucru cu job-uri.
 * Permite:
 *  - Lansarea unui job.
 *  - Monitorizarea executiei job-ului.
 *  - Consumarea rezultatului.
 *
 * User: vitalie.babalunga@greensoft.com.ro
 * Date: 18.10.2013 16:13
 */

var JOB_BUTTON_STATUS = {
    INITIAL: {
        code: "i",
        text: ""
    },

    RUNNING: {
        code: "r",
        text: "În curs ..."
    },

    DOWNLOAD: {
        code: "d",
        text: "Descarcă fişier ..."
    },

    ERROR: {
        code: "e",
        text: "Eroare ..."
    }
};

function JobButton(opt, refNodeId) {
    this.opt = opt;
    //jobId :
    //jobData :
    //jobStartAction :
    //jobStatusAction :

    this.node = $(refNodeId);

    this.initialText = this.getNodeText();

    this.state = JOB_BUTTON_STATUS.INITIAL;


    this.jobRequestId = null;
    this.jobId = this.opt.jobId;

    var self = this;
    this.node.onclick = function () {
        self.onClickHandler();
    }
};


JobButton.prototype = {
    onClickHandler: function () {
        var self = this;

        if (self.state == JOB_BUTTON_STATUS.INITIAL) {
            self.startJob();
            self.setState(JOB_BUTTON_STATUS.RUNNING);
            return;
        }

        if (self.state == JOB_BUTTON_STATUS.RUNNING) {

            return;
        }

        if (self.state == JOB_BUTTON_STATUS.DOWNLOAD) {
            self.launchDownload();
            self.setState(JOB_BUTTON_STATUS.INITIAL);
        }

        if (self.state == JOB_BUTTON_STATUS.ERROR){
            self.showError();
            self.setState(JOB_BUTTON_STATUS.INITIAL);


        }

    },

    startJob: function () {
        var self = this;

//        setTimeout(function () {
//            self.setState(JOB_BUTTON_STATUS.DOWNLOAD);
//        }, 5000);

//        return;

        //todo: Utilizare prototype/jquery pentru lansare cerere ajax spre action job-start
        new Ajax.Request(self.opt.jobStartAction,
            {
                method: 'post',
                //parameters: "t=" + new Date().getTime() + "&jobId=" + self.jobId + "&jobData=" + encodeURIComponent(Form.serialize(self.opt.jobData.form)),
                parameters: "t=" + new Date().getTime() + "&jobId=" + self.jobId + "&" + Form.serialize(self.opt.jobData.form),
                onComplete: function (originalRequest) {
                    var response = getResponseMesg(originalRequest.responseText);
                    try {
                        self.onStartJobSuccess(eval("(" + response + ")"));
                    } catch (e) {
                        if( console) console.log("Eroare la evaluare response action start job", e, e.message);
                    }
                },
                onFailure: function (error) {
                    self.onError(error);
                }
            });
    },

    onStartJobSuccess: function (data) {
        var self = this;
        self.error = data.error;
        if (self.error.length > 0) {
            alert(self.error);
        } else {
            self.jobRequestId = data.jobRequestId;
            if (self.jobRequestId > 0) {
                self.startJobMonitoring();
            }
        }
    },

    startJobMonitoring: function () {
        var self = this;
        self.checkJobStatus();
    },

    checkJobStatus: function () {
        var self = this;
//        setTimeout(function () {
//            self.setState(JOB_BUTTON_STATUS.DOWNLOAD);
//        }, 5000);

        new Ajax.Request(self.opt.jobStatusAction,
            {
                method: 'post',
                parameters: "jobRequestId=" + self.jobRequestId,
                onComplete: function (originalRequest) {
                    var response = getResponseMesg(originalRequest.responseText);
                    try {
                        self.onStopJobMonitoring(eval("(" + response + ")"));
                    } catch (e) {
                        if( console) console.log("Eroare la evaluare response action check status job", e, e.message);
                    }
                },
                onFailure: function (error) {
                    self.onError(error);
                }
            });
    },

    onStopJobMonitoring: function (data) {
        var self = this;
        self.jobStatus = data.jobStatus;
        self.jobResult = data.jobResult;
        self.jobSuccess = data.jobSuccess;
        self.jobRequestId = data.jobRequestId;

//        alert("id= " + self.jobRequestId + "success=" +self.jobSuccess);

        /*finalizare cu success*/
        if (self.jobSuccess == 'true' && self.jobStatus == 'D') {
            /*setez btn pt download*/
            self.setState(JOB_BUTTON_STATUS.DOWNLOAD);
            return;
        }
        else {
        /*finalizare cu eroare*/
        if (self.jobSuccess == 'false' && self.jobStatus == 'D') {
            self.setState(JOB_BUTTON_STATUS.ERROR);
            return;
        }
        else {
             self.checkJobMonitoring();
           }
        }
    },

    checkJobMonitoring: function () {
        var self = this;
        self.jobStatusTimerId = setTimeout(function () {
            self.checkJobStatus();
        }, 1000);
    },

    setState: function (state) {
        this.state = state;
        this.setNodeText();
    },

    setNodeText: function () {
        var text = this.state.text;
        if (this.state == JOB_BUTTON_STATUS.INITIAL) {
            text = this.initialText;
        }

        if (this.node.tagName.toUpperCase() == "INPUT") {
            this.node.value = text;
        } else {
            this.node.innerHTML = text;
        }
    },

    getNodeText: function () {
        if (this.node.tagName.toUpperCase() == "INPUT") {
            return this.node.value;
        } else {
            return this.node.innerHTML;
        }
    },

    onResultAvailable: function () {
        var self = this;

        self.state = JOB_BUTTON_STATUS.DOWNLOAD;
        self.setNodeText();
    },

    onError: function (error) {
        if( console) console.log("Eroare la lansare job", error, arguments);
    },

    launchDownload: function () {
        var self = this;
        window.location.href = self.opt.downloadFileFromRepo + "&jobResult=" + self.jobResult;
    },

    showError: function(){
        var self = this;
        alert(self.jobResult);
    }
}
