//var appsPrinterId;
//var cameraInterval;
var PrinterInfoInterval;
var path = '/joystick/send_command';
function cJoystickClass(appStrid){
    var t = this;
    this.root = $("#"+appStrid+"_popup");
    this.printerId = null;
    this.printerName = null;
    this.state = null;
    this.appStrid = appStrid;
    this.url = null;
    this.interval = 3000;
    this.intervalId = null;
    this.intervalView = 1000;
    this.intervalViewId = null;
    this.paneApi = null;
    this.job_id = null;
    this.showBtn = null;
    this.closeBtn = ".close";
    this.getAppSettings = null;
    this.settings = {'temperatures':{},'moveStep':10,moveSpeed:300};
    this.logStack = [];
    this.currentTemp = {"left":0,"right":0,"bed":0};
    this.materials = {
        'default':{'left':{'min':0,'max':350},'right':{'min':0,'max':350},'bed':{'min':0,'max':200}},
        'abs':{'left':{'min':0,'max':250,'default':150},'right':{'min':0,'max':200,'default':150},'bed':{'min':0,'max':150,'default':120}},
        'pla':{'left':{'min':0,'max':250,'default':200},'right':{'min':0,'max':300,'default':250},'bed':{'min':0,'max':100,'default':80}}
    };
    this.init = function(){
        if (!this.root){
            return;
        }
        this.settings.temperatures = {
            'left':{'min':0,'max':350},
            'right':{'min':0,'max':350},
            'bed':{'min':0,'max':10}
        }
        if (this.url == null){
            this.url = "/apps/"+this.appStrid+"/";
        }

        if (this.showBtn == null){
            this.showBtn = "."+this.appStrid+"-btn";
        }

        this.root.find(this.closeBtn).click(function () {
            t.hidePopup();
        });

        this.root.find('.joc-close').click(function () {
            t.hidePopup();
        });

        this.root.find('.footer .start .red').click(function () {
            t.setStep('work');
        });

        this.root.find('.footer .stop .blue').click(function(){
            window.location.reload();
        });

        this.root.find('h1 span').click(function(){
            // t.setTab(this.id);
        });

        this.root.find('.threejs-nav li.tab-show').click(function(){
            t.setTab(this.id);
            $('.threejs-nav li.tab-show').removeClass('active-tab');
            $(this).addClass('active-tab');
        });

        this.root.find('.viewer div').html('Initialization...');

        this.root.find('.execute').click(function(){
            var val = t.root.find('[name=command]').val();
            t.putMessage(val);
        });
        this.root.find('.temperature .radio .btn').click(function(){
            //t.setOnOff(this);
            var ext = $(this).parents('fieldset').data('ext');
            setExtruderTemperature(ext,0);
        });

        this.root.find('.temperature .btn-set').click(function(){
            //t.setOnOff(this);
            var ext = $(this).parents('fieldset').data('ext');
            setExtruderTemperature(ext,$(this).prev().val());
        });


        this.root.find('[name=material]').change(function(){
            t.changeMaterial(this.value);
        });

        this.root.find('.temperature input[type=number]').change(function(){
            t.checkTemperature(this);
        });
        this.root.find('.joystick_jog .steps a').click(function(){
            t.setMoveStep(this);
        });
        /*
        this.root.find( ".speedslider" ).slider({
            value:300,
            min: 1,
            max: 600,
            step: 10,
            slide: function( event, ui ) {
                t.root.find('.speeddisplay').text(ui.value)
                    .css('left',jQuery(ui.handle).css('left'));
                t.settings.moveSpeed = parseInt(ui.value);
            }
        });
        */
        jQuery(this.showBtn).click(function(){
            var id = jQuery('.apps-block').data('printer-id');
            t.printerId = id;
            t.printerName = jQuery('.apps-block').data('printer-name');
            t.showPopup();
            //t.initCanvas();
        });

    }
    this.initCanvas = function(){
        //Init joystick
        var canvas;
        var ctx;
        var canvas_v;
        var ctx_v;
        var x = 11;
        var y = 11;
        var dx = 11;
        var dy = 11;
        var x_v= 0;
        var y_v = 0;
        var dx_v = 11;
        var dy_v = 11;

        var WIDTH = parseFloat($('.apps-block').data('printer-x')*0.5);
        var HEIGHT = parseFloat($('.apps-block').data('printer-y')*0.5);
        var WIDTH_V = 35;
        var HEIGHT_V = parseFloat($('.apps-block').data('printer-z')*0.5);

        $('#canvas').attr( "width", WIDTH );
        $('#canvas').attr( "height", HEIGHT );
        $('#canvas_tool').attr( "width", WIDTH );
        $('#canvas_tool').attr( "height", HEIGHT );

        $('#canvas_v_wrap').attr( "height", HEIGHT_V );
        $('#canvas_v_wrap').attr( "width", WIDTH_V  );
        $('#canvas_v').attr( "height", HEIGHT_V );
        $('#canvas_v').attr( "width", WIDTH_V  );


        var extruder = $("input[name='extruder']:checked").val();
        var bg = new Image();
        var bg_v = new Image();
        var j_disabled = new Image();
        var j_active = new Image();
        var j_vertical = new Image();

        bg.src = getConst("cdn_url") + "/assets/apps/joystick/img/canv_bg.png";
        bg_v.src = getConst("cdn_url") + "/assets/apps/joystick/img/vcanvas.png";
        j_disabled.src = getConst("cdn_url") + "/assets/apps/joystick/img/j_disabled.png";
        j_active.src= getConst("cdn_url") + "/assets/apps/joystick/img/j_active.png";
        j_vertical.src= getConst("cdn_url") + "/assets/apps/joystick/img/j_vertical.png";

        function rect(x,y,w,h) {
            ctx.beginPath();
            ctx.rect(x,y,w,h);
            ctx.closePath();
            ctx.fill();
            ctx.stroke();
        }
        function rect_v(x,y,w,h) {
            ctx_v.beginPath();
            ctx_v.rect(x,y,w,h);
            ctx_v.closePath();
            ctx_v.fill();
            ctx_v.stroke();
        }
        function clear() {
            ctx.clearRect(0, 0, WIDTH, HEIGHT);
            ctx_v.clearRect(0, 0, WIDTH_V, HEIGHT_V);
        }


        function draw() {
            clear();
            var pattern_bg = ctx.createPattern(bg, "repeat");
            ctx.fillStyle = pattern_bg;
            ctx.strokeStyle = "white";
            var pattern_bg_v = ctx_v.createPattern(bg_v, "repeat");
            ctx_v.fillStyle = pattern_bg_v;
            ctx_v.strokeStyle = "white";
            rect(0, 0, WIDTH, HEIGHT);
            rect_v(0, 0, WIDTH_V, HEIGHT_V);
            ctx_v.drawImage(j_vertical, x_v, y_v);
            if(extruder=='left'){
                ctx.drawImage(j_disabled, x, y);
                ctx.drawImage(j_active, x-11, y);
            }else{
                ctx.drawImage(j_active, x, y);
                ctx.drawImage(j_disabled, x-11, y);
            }
        }
        canvas = document.getElementById("canvas");
        ctx = canvas.getContext("2d");
        canvas_v = document.getElementById("canvas_v");
        ctx_v = canvas_v.getContext("2d");
        j_interval = setInterval(draw, 10);
        function coordinates(x, y, z){
            $("#x").val(x);
            $("#y").val(y);
            $("#z").val(z);
            console.log(x+"/"+y+"/"+z);
        }
        function move_v(pos){
            switch(pos){
                case 'top':
                    if (y_v - dy_v >= 0){
                        y_v -= dy_v;
                    }
                    break;
                case 'bot':
                    if (y_v + dy_v <= HEIGHT_V){
                        y_v += dy_v;
                    }
                    break;
            }
            coordinates(x, y, y_v);
        }

        function move(pos){
            switch(pos){
                case 'top':
                    if (y - dy >= 0){
                        y -= dy;
                    }
                    break;
                case 'bot':
                    if (y + dy <= HEIGHT-11){
                        y += dy;
                    }
                    break;
                case 'left':
                    if (x - dx > 0){
                        x -= dx;
                    }
                    break;
                case 'right':
                    if (x + dx <= WIDTH){
                        x += dx;
                    }
                    break;
            }
            coordinates(x, y, y_v);
        }


        $( "#arr_top_v" ).click(function() {
            move_v('top');
        });

        $( "#arr_bot_v" ).click(function() {
            move_v('bot');
        });


        $( "#arr_top" ).click(function() {
            move('top');
        });

        $( "#arr_bot" ).click(function() {
            move('bot');
        });


        $( "#arr_left" ).click(function() {
            move('left');
        });


        $( "#arr_right" ).click(function() {
            move('right');
        });

        $( "#home" ).click(function() {
            y = HEIGHT-16;
            x = 11;
        });

        $( "#home_x" ).click(function() {
            x = 11;
        });

        $( "#home_y" ).click(function() {
            y = HEIGHT-16;;
        });

        $( "#home_z" ).click(function() {
            y_v = HEIGHT_V-11;
        });

        $('input[type=radio][name=extruder]').on('change', function(){
            extruder = $(this).val();
        });

        $('#speed a').click(function() {
            $( "#speed a" ).removeClass( "act" );
            $(this).addClass( "act" );
            console.log($(this).attr("id"));
        });

        $('#btn').click(function() {
            alert("Stop!");
        });
    }
    this.setMoveStep = function(el){
        el = jQuery(el);
        this.settings.moveStep = parseFloat(el.text());
        el.parent().find('.btn').removeClass('selected');
        el.addClass('selected');
    };
    this.updatePrinterStatus = function(){
        for(var i in this.currentTemp){
            this.root.find(".temperature .ext"+i+" .value").html(this.currentTemp[i]+"&deg;C");
            this.checkCurrenTemp(i);
        }
    }
    this.checkCurrenTemp = function(type){
        var el =this.root.find(".ext"+type+" .value");
        var temp = parseInt(el.text().substr(0,el.text().length-2));
        if (temp > this.settings.temperatures[type].max*0.9){
            el.removeClass('green');
            el.addClass('hot');
        } else {
            el.removeClass('hot');
            el.addClass('green');
        }
    }
    this.checkTemperature = function(el){
        var type = el.name.substr(3);
        if (el.value > this.settings.temperatures[type].max){
            el.value = this.settings.temperatures[type].max;
        } else if (el.value < this.settings.temperatures[type].min){
            el.value = this.settings.temperatures[type].min;
        }
    }
    this.changeMaterial = function(material){
        if (this.materials[material] != undefined){
            for( var i in this.currentTemp){
                this.settings.temperatures[i].min = this.materials[material][i].min;
                this.settings.temperatures[i].max = this.materials[material][i].max;
                this.root.find('[name=ext'+i+']').val(this.materials[material][i].default);
            }
        }
    }

    this.setOnOff = function(el){
        var el = jQuery(el);
        //var ext = el.parents('fieldset').data('ext');
        if (el.hasClass('green')){
            el.removeClass('green');
            el.addClass('gray');
            el.text('Off');
            el.parent().find('.but').removeClass('on');
            /*if (this.root.find('.temperature .radio .on').get(0) == undefined){
             clearInterval(this.intervalId);
             this.intervalId = null;
             }*/
            //setExtruderTemperature(ext,0);
        } else {
            el.removeClass('gray');
            el.addClass('green');
            el.text("On");
            el.parent().find('.but').addClass('on');
            //this.startInterval();
            //setExtruderTemperature(ext,el.parent().prev().val());
        }
    }
    this.startInterval = function(){
        if (this.intervalId == null){
            this.intervalId = setInterval(function(){
                for(var i in t.currentTemp){
                    t.currentTemp[i]++;
                }
                t.updatePrinterStatus();
            },this.interval);
        }

    }
    this.updateLiveView = function(){
        $.ajax({
            url: '/ajax/getLiveView',
            type: 'POST',
            dataType: 'json',
            data: { printer_id:this.printerId},
            success: function (response) {
                if (response.success) {
                    if (response.result.is_printer_connected == 'f') {
                        t.root.find('.viewer div').html('Please turn 3D printer on or check USB connection of 3D printer. Camera do not operate without printer for privacy issues.');
                        return;
                    }
                    if (response.result.web_cam == 't') {
                        t.root.find('.viewer div').html('<img src="data:image/jpeg;base64,' + response.result.image + '" />');
                    } else {
                        t.root.find('.viewer div').html('Please check USB connection of camera.');
                    }
                }
                else {
                    console.error(response.result);
                }
            }
        });
    }
    this.getSettings = function(){
        if (this.getAppSettings != null){
            this.settings = this.getAppSettings();
        }
        this.settings.file_id = this.fileId;
        return this.settings;
    }
    this.setTab = function (tab){
        this.root.find('h1 span').addClass('disabled');
        this.root.find('h1 #'+tab).removeClass('disabled');
        this.root.find('.popup_tab').hide();
        this.root.find("."+tab).show();
    }

    this.callApi = function(){
        var url = this.url + "convert/"+this.fileId;
        var data = {};
        for (var i in this.settings){
            data["settings_"+i] = this.settings[i];
        }

        $.ajax({
            url: url,
            data: data,
            type: "POST",
            dataType: 'json',
            success: function (result) {
                if (result.error == false){
                    t.job_id = result.job_id;
                    t.getStatus();
                    t.intervalId = setInterval(function(){t.getStatus();},t.interval);
                } else {
                    t.putMessage(result.error);
                }

            }
        });

    }
    this.getStatus = function(){

        var url = this.url + "getstatus/"+this.job_id;
        $.ajax({
            url: url,
            type: "POST",
            dataType: 'json',
            success: function (result) {
                if (result.error == false){
                    t.resetStatus(result);
                } else {
                    t.putMessage(result.error);
                    t.setStep('stop');
                }
            }
        });
    }
    this.putMessage = function (message){
        var div = document.createElement("div");
        div.innerHTML = message;
        this.root.find('.logs .jspPane').append(div);
        this.paneApi.reinitialise();
        this.paneApi.scrollToBottom();
    }
    this.hidePopup = function(){
        clearInterval(this.intervalId);
        clearInterval(this.intervalViewId);
        action_console_close();
        disablePopupsBlur();
        this.root.fadeOut();

    }

    this.showPopup = function(){
        hideAllPopups();
        enablePopupsBlur();
        this.setTab('joystick_jog');
        this.root.find('.name span.name').text(this.printerName);
        /*
         this.intervalViewId = setInterval(function(){
         t.updateLiveView();
         },this.intervalView);*/
        this.root.fadeIn();
        if (this.paneApi == null){
            this.paneApi = this.root.find('.logs .cont').jScrollPane().data('jsp');
        }
    }
}
function setExtruderTemperature(ext,arg){
    arg = parseInt(arg);
    if(!arg){
        arg = 0;
    }
    switch (ext) {
        case 'extleft':
            ext = "set_extruder_temp";
            break
        case 'extright':
            ext = "set_extruder_temp";
            break
        case 'extbed':
            ext = "set_bed_temp";
            break
    }

    setComandData(ext,arg);

}
function setPrinterInfo(data){
    $('.printer-sensors .x-position .data').text(data.coordinate.x);
    $('.printer-sensors .y-position .data').text(data.coordinate.x);
    $('.printer-sensors .z-position .data').text(data.coordinate.z);
    $('.printer-sensors .e-position .data').text(data.coordinate.x);
    $('.printer-sensors .t-heatbed .data').text(data.bed.temp);
    $('.printer-sensors .t-extruder .data').text(data.extruder.temp);
    if (data.log) {
        renderLog(data.log);  
    };

/*    $('.box-heatbed .temperature span').text(temps[0])
    $('.box-right-extruder .temperature span').text(temps[1])


    var target_temps =  JSON.parse(info.target_temps);

    $('fieldset.extbed .value').text(temps[0] + ' C');
    $('fieldset.extright .value').text(temps[1] + ' C');
    if(temps[2] != undefined){
        $('fieldset.extleft').show();
        $('fieldset.extleft .value').text(temps[2] + ' C');
        setButStatus($('fieldset.extleft .but'),target_temps[2]);
    }else{
        $('fieldset.extleft').hide();
    }
    setButStatus($('fieldset.extright .but'),target_temps[1]);
    setButStatus($('fieldset.extbed .but'),target_temps[0]);*/

}
function setButStatus(selector,num){
    if(num > 0){
        selector.addClass('on');
    }else{
        selector.removeClass('on');
    }
}
function getLiveViewJoystick(data){
    if(data.result){
        if(data.message.webcam_image == ""){
            $('#joystick_popup .live_view .cam').html('<img style="width:100%;" src="https://d19x0umjofh4ry.cloudfront.net/assets/i/liveview/no_camera_grey.gif" />');
        }else{
            var myImage = new Image();
            myImage.src = 'data:image/jpeg;base64,' +  data.message.webcam_image;
            myImage.onload = function () {
                $('#joystick_popup .live_view .cam').html('<img style="width:100%;" src="'+ myImage.src +'" />');
            }
        }
    }else{
        $('#joystick_popup .viewer .cam').text('Please turn 3D printer on or check USB connection of 3D printer. Camera do not operate without printer for privacy issues.');
    }
}
function setComandData(command,value){

    var setdata = {
        'printer_id': printer_id,
        'command': command,
        'value': value
    };
    $.post(path,setdata,function(data){
        console.log(data);
    });

}
function sendSpeed(){
    var xySpeed = $('#xy-speed').val();
    var zSpeed  = $('#z-speed').val();
    setComandData('set_speed',xySpeed);
    setComandData('set_speed_z',zSpeed);
}
function sendExtruderSpeed(){
    var speed = $('.box-extruder #extspeed').val();
    setComandData('set_extruder_speed',speed);
}
function jogXYClick(val){
    ///setComandData(appsPrinterId,'','')
    var com = val[0];
    var arg = val.substring(1, val.length);

    setComandData(com,arg);
}
function jogZClick(val){
    setComandData('move',val);
}
function runCommandSilent(val){
    setComandData(val, null);
}
function setStop(){
    $.post('/joystick/restart_printer',{'printer_id':printer_id},function(data){
        console.log(data);
    });
}
function setFanStatus(arg){
    setComandData(arg, null);
}


// console
function sendRequest(gcode_string) {
    $.post('/joystick/send_gcode', {'printer_id': printer_id, 'gcode_string': gcode_string}, function(data) {
        clearInput();
        renderLog('User: ' + gcode_string + '\n');
    });
};
$(document).on('keyup','#console_input', function(e) {
    if (e.keyCode == 13) {
        sendRequest($(this).val())
    }
});
function renderLog(log_string) {
    var $log = $('#log');
    $log.text($log.text() + log_string);
    var block = document.getElementById("log");
    block.scrollTop = block.scrollHeight;
};
function clearInput() {
    $('#console_input').val('');
};

// $
$(document).ready(function() {
    window.joystick = new cJoystickClass("joystick");
    window.joystick.init();
    getPrinterInfo();

    $(document).on('click','.apps-btn', function(){
        appsPrinterId = $(this).data('printer-id');
    });


    function getPrinterInfo(){
    console.log('Start function')
        $('#joystick_popup .live_view .cam').html('<img style="width:100%;" src="https://d19x0umjofh4ry.cloudfront.net/assets/i/liveview/no_camera_grey.gif" />');
        sendSpeed();
        sendExtruderSpeed();
        clearInterval(PrinterInfoInterval);

        PrinterInfoInterval = setInterval(function(){
            $.post('/joystick/get_printer_info', {'printer_id':printer_id}, setPrinterInfo);
        }, 500, 'json');

        $('#joystick_popup .threejs-nav li').removeClass('active-tab')
        $('#joystick_popup .threejs-nav li#joystick_jog').addClass('active-tab');
    };

    $('.sendSpeed input').focusout(function(){
        sendSpeed();
    })

    $('.box-extruder #extspeed').focusout(function(){
        sendExtruderSpeed();
    })

    $('#joystick_popup .close').click(function(){
        //clearInterval(cameraInterval);
        clearInterval(PrinterInfoInterval);
        action_console_close();


    });

    $('#joystick_extruders').click(function(){
        /*
         PrinterInfoInterval = setInterval(function(){
         getPost('/a/print/get_printer_info/', {'printer_id':appsPrinterId}, setPrinterInfo);
         },2000);
         */
    });

    // retract
    $('button.retract').click(function(){
        var amount = $('.box-extruder input#eamount').val();
        var ext = 'extrude';
        setComandData(ext, '-' + amount);
    });
    $('button.extrude').click(function(){
        var amount = $('.box-extruder input#eamount').val();
        var ext = 'extrude';
        setComandData(ext, amount);
    });

    $('.btn-set-right-extruder').click(function(){
        var setData = $(this).prev().val();
        if(setData != ""){
            setComandData('set_extruder_temp',setData);
        }
    });

    $('.btn-set-heatbed').click(function(){
        var setData = $(this).prev().val();
        if(setData != ""){
            setComandData('set_bed_temp',setData);
        }
    });
    $('.joystick_extruders .eamount-btn').click(function(){

        var eamount = parseInt( $(this).text() );
        $('#eamount').val(eamount);
    });
});
