
/////////////////////////////
/// Sequencer
/////////////////////////////

$("#start-sequencer").on("click", function(e){
    console.log("clicked "+$(this))
    var data = $("#ob-list-options-sequencer").val()
    console.log(data)
    $(this).crud("POST", "/api/sequencer/run", data)
})

$("#stop-sequencer").on("click", function(e){
    $(this).crud("DELETE", "/api/sequencer/run")
})

$("#pause-sequencer").on("click", function(e){
    $(this).crud("PUT", "/api/sequencer/run", false)
})

$("#resume-sequencer").on("click", function(e){
    $(this).crud("PUT", "/api/sequencer/run", true)
})

$("#repeat-sequencer").on("click", function(e){
    $(this).crud("PUT", "/api/sequencer/run", null)
})

//////////////////
/// Blocks
//////////////////

$("#ob-list-options-editor").on("change", function(e){
    e.preventDefault();
    var val = $(this).val();
    console.log(val)
    section_id = $("section").attr("id");
    console.log(section_id);
    if (section_id=="ob-list" && val!=null){
        $.get(val,
              {included : true},
              function(data){
                  //console.log(data)
                  $("#ob-list").html(data)
              })
    }
}).trigger("change")


$(document).on("click", "#create-ob", function(e){
    e.preventDefault();

        var name = $("#new-ob-name").val()
        
    var data = $("#new-ob-name").val()
    $(this).crud("POST", "/api/blocks/", data).then(function(e){
        location.href = data;
    })
    
});

$(document).on("click","#update-ob", function(e){
    e.preventDefault();

        form = $("form")

        var data = [];
        $("section", form).each(function(e) {
            
            var template_id = $(this).attr("data-template")
            var template_name = $(this).attr("data-template")
            var raw_template = {};
            
            $("fieldset", this).each(function(e) {
                
                var setup_name = $(this).attr("data-subsystem")
                var setup_array = $(this).serializeArray()
                var raw_setup = {}
                
                $.each(setup_array, function() {
	            raw_setup[this.name] = this.value;
                });
                
                raw_template["TPLID"] = template_id
                raw_template["TPLName"] = template_name
                raw_template[setup_name] = raw_setup
                
            });
            
            data.push(raw_template)
        });

        console.log(data)       
    var name = $("form").data("name")
    
    $(this).crud("PUT", "/api/blocks/"+name, data)
    
});

$(document).on("click", "#delete-ob", function(e){
    e.preventDefault();
    
    var name = $("form").data("name")
    var form = $("form[data-name='"+name+"']")

    $(this).crud("DELETE", "/api/blocks/", name).then(function(e){
        form.fadeOut(500, function(){ $(this).remove()})
        location.href = "./"
    })
    
});

$(document).on("click",'[data-control="delete-template-instance"]', function(e){
    e.preventDefault();

         var name = $(this).data("name")
         var instance = $(this).data("instance")
         var fieldset = $("fieldset[data-instance="+instance+"]")
         console.log(name, instance)
      
    $(this).crud("DELETE", "/api/blocks/"+name, instance-1).then(function(e){
        $("input", fieldset).css("border","1px solid red")
        fieldset.fadeOut(500, function(){ $(this).remove()})
    })
});

// Reload on list selection
$(document).on("change","#tpl-list-options", function(e){
    e.preventDefault();
    var name = $("form").data("name")
    var data = $(this).val()

    $(this).crud("POST", "/api/blocks/"+name, data).then(function(e){
        location.reload()
    })

});

// Reload on list selection
$('[data-parameter="blocks-list-options"]').on("change", function(e){
    var val = $(this).val()
    if (val!=null){
        $.get(val, {included:true}, function(data){
            $("#ob-list").html(data)
        })
    }
}).trigger("change")

/////////////////////////////
/// Devices
/////////////////////////////

$("#selectall").click(function(){
    var checked = this.checked
    $('input:checkbox').not(this).prop('checked', checked);
    $('input:text, select').prop('disabled', !checked);

});

$("form").submit(function(e){
    e.preventDefault();
    console.log("click")

    var motion = "named" // $('[name="motion"]:checked').val()
    var action = $(this).find("input[type=submit]:focus" ).attr("id");
    var data = {};

    $.each($("#device_values").serializeArray(), function() {
	data[this.name] = this.value;
    });

    if (action == "move") {
        $(this).crud("PUT", "/api/devices", {"motion": motion, "data": data})
    } else if (action == "home") {
        $(this).crud("POST", "/api/devices", {"motion": motion, "data": data})
    } else if (action == "abort") {
        $(this).crud("DELETE", "/api/devices", {"motion": motion, "data": data})
    }
    else {
    }

})

/////////////////////////////
/// Derotation
/////////////////////////////

$("#start-drot").click(function(e){
    e.preventDefault()
    drot_mode_list = document.getElementById("drot-mode")
    var action = "Start_Tracking"
    var selected_mode = drot_mode_list.options[drot_mode_list.selectedIndex].text
    var pos_ang = $("#OBS_PosAng").val()
    $(this).crud("PUT", "/api/devices/derotation", [action, selected_mode, pos_ang])
})

$("#stop-drot").click(function(e){
    e.preventDefault()
    var action = "Stop_Tracking"
    $(this).crud("PUT", "/api/devices/derotation", [action, null, null])

})

$("#drot-mode").change(function(e){
    e.preventDefault()
    drot_mode_list = document.getElementById("drot-mode")
    var selected_mode = drot_mode_list.options[drot_mode_list.selectedIndex].text
    console.log(selected_mode)
    if(selected_mode == "FIELD_FIXED") {
        document.getElementById("OBS_PosAng").disabled = false
    }
    else{
        document.getElementById("OBS_PosAng").disabled = true
        //document.getElementById("OBS_PosAng").val() = 0
    }

})

/////////////////////////////
/// Soul
/////////////////////////////

$("#move-soul").click(function(e){
    e.preventDefault()
    var cx = $("#cx_S").val()
    var cy = $("#cy_S").val()
    //$(this).crud("PUT", "/api/devices/externals/soul", [cx, cy])
    $(this).crud("PUT", "/api/devices/externals/soul", [cx, cy]).then(function(o){
        console.stdlog = console.log.bind(console);
        console.logs = [];
        console.logs.push(Array.from(arguments));
        var res = console.logs[0];
        var status = res[0][0];
        var steps = res[0][1];
        console.log(res);
        $('[data-status="soul-deltas"]').text(steps)
    })

})

$("#calculate-soul").click(function(e){
    e.preventDefault()
    var cx = $("#cx_S").val()
    var cy = $("#cy_S").val()
    $(this).crud("POST", "/api/devices/externals/soul", [cx, cy]).then(function(o){
        console.stdlog = console.log.bind(console);
        console.logs = [];
        console.logs.push(Array.from(arguments));
        var res = console.logs[0];
        var status = res[0][0];
        var steps = res[0][1];
        console.log(res);
        $('[data-status="soul-deltas"]').text(steps)
    })

})

/////////////////////////////
/// DM
/////////////////////////////

$("#dm-modal").click(function(e){ //change(function(e){
    e.preventDefault
    var modal = true
    idList = ['act' , 'strain' , 'move-zonal']
    $(this).crud("POST", "/api/dm/zonal", modal).then(function(o){
        for(let i = 0; i<idList.length; i++) {
            document.getElementById(idList[i]).disabled = modal
        }
    })

    console.log("MODAL MODE: Event change worked!")
})

$("#dm-zonal").click(function(e){ //change(function(e){
    e.preventDefault
    var modal = false
    idList = ['act' , 'strain' , 'move-zonal']
    $(this).crud("POST", "/api/dm/zonal", modal).then(function(o){
        for(let i = 0; i<idList.length; i++) {
            document.getElementById(idList[i]).disabled = modal
        }
    })

    console.log("ZONAL MODE: Event change worked!")
})

$("#move-zonal").click(function(e){
    e.preventDefault()
    var actuator = $("#act").val()
    var strain   = $("#strain").val()
    $(this).crud("PUT", "/api/rtc/mode/zonal/"+actuator, strain)
})

$("#start-ncpa-rot").click(function(e){
    e.preventDefault()
    console.log("START NCPA ROTATION")
    var action = "start"
    $(this).crud("PUT", "/api/dm/rotation", action)
})

$("#stop-ncpa-rot").click(function(e){
    e.preventDefault()
    console.log("STOP NCPA ROTATION")
    var action = "stop"
    $(this).crud("DELETE", "/api/dm/rotation", action)

})

$("#create-ncpa").click(function(e){
    e.preventDefault()
    $(this).crud("POST", "/api/dm/ncpa")
})

$("#load-ncpa").click(function(e){
    e.preventDefault()
    var ncpa = $("#ncpa-list").val()
    console.log(ncpa)
    $(this).crud("PUT", "/api/dm/ncpa", ncpa)
})

$("#flatten-dm").click(function(e){
    e.preventDefault()
    $(this).crud("DELETE", "/api/dm/shape")
})

$('[data-rtc="tt"]').click(function(e){
    e.preventDefault()
    var amount = $("#tiptilt-amount").val()
    var sign = $(this).data("sign")
    var mode = $(this).data("mode")
    var ref = ""

    var modes = [0, 0, 0, 0]
    if ($(this).attr("id") != "tiptilt-reset"){
        if(document.getElementById('teccam-ref').checked){
            console.log($('#teccam-ref').val())
            modes[mode] = sign*amount
        }
        else if(document.getElementById('scicam-ref').checked){
            console.log($('#scicam-ref').val())
            modes[mode] = sign*amount
            modes = [modes[0], modes[0], modes[2], -modes[3]]
        }
    } else {
        modes = null
    }
    $(this).crud("PUT", "/api/dm/tiptilt", modes, ref)
})

$("#create-flat").click(function(e){
    e.preventDefault()
    $(this).crud("POST", "/api/dm/flat")
})

$("#load-flat").click(function(e){
    e.preventDefault()
    var flat = $("#flat-list").val()
    console.log(flat)
    $(this).crud("PUT", "/api/dm/flat", flat)
})

/////////////////////////////
/// RTC
/////////////////////////////

$("#call-samples").click(function(e){
    e.preventDefault()
    var samples = $("#samples").val()
    $(this).crud("PUT", "/api/rtc/cloud", samples)
    // $(this).crud("PUT", "/api/rtc/cloud", samples).then(function(o){
    //     $('[data-status="cloud_samples"]').text(samples)
    // })
})

$("#open-loop").click(function(e){
    e.preventDefault()
    $(this).crud("DELETE", "/api/rtc/loop")
})

$("#close-loop").click(function(e){
    e.preventDefault()
    $(this).crud("POST", "/api/rtc/loop")
})

$("#update-pid").click(function(e){
    e.preventDefault()
    var pid = [
        $("#TTPIDKP").val(),
        $("#TTPIDKI").val(),
        $("#TTPIDKD").val(),
        $("#TTPIDTF").val(),
        $("#TTPIDTS").val(),
    ]
    $(this).crud("PUT", "/api/rtc/pid", pid)
})

$("#set-frequency").click(function(e){
    e.preventDefault()
    var freq = $("#frequency").val()
    $(this).crud("PUT", "/api/rtc/loop/frequency", freq)
})

$("#snapshot").click(function(e){
    e.preventDefault()
    $(this).crud("POST", "/api/rtc/snapshot")
})

// $("#teccam").click(function(e){
//     e.preventDefault()
//     $(this).crud("POST", "/api/rtc/teccam")
// })

$("#teccam-custom").click(function(e){
    e.preventDefault()
    var data = $("#teccam-input").val()
    console.log(data)
    $(this).crud("PUT", "/api/rtc/command", data).then(function(o){
        $("#teccam-output").text(o)
    })
})

$("#reset-rtc").click(function(e){
    e.preventDefault()
    $(this).crud("POST", "/api/rtc/reset")
})

$("#resurrect-rtc").click(function(e){
    e.preventDefault()
    $(this).crud("POST", "/api/rtc/resurrect")
})

/////////////////////////////
/// TECCAM
/////////////////////////////

// Input form
$("#update-centroid").click(function(e){
    e.preventDefault()
    var cx = $("#cx").val()
    var cy = $("#cy").val()
    $(this).crud("PUT", "/api/teccam/centroid", [cx, cy])
})

// Point and click
$("#cred").click(function(e){
    var parentOffset = $(this).parent().offset();
    //or $(this).offset(); // Element offset
    var relX = e.pageX - parentOffset.left;
    var relY = e.pageY - parentOffset.top;

    var cx = - ( ( (relX / $(this).width()) * 2.0 ) - 1)
    var cy = + ( ( (relY / $(this).height()) * 2.0 ) - 1)

    $("#cx").val(cx.toFixed(2))
    $("#cy").val(cy.toFixed(2))
    $(this).crud("PUT", "/api/teccam/centroid", [cx, cy])

    console.log(cx, cy)

});

$("#create-dark").click(function(e){
    e.preventDefault()
    $(this).crud("POST", "/api/teccam/dark")
})

$("#load-dark").click(function(e){
    e.preventDefault()
    var dark = $("#dark-list").val()
    $(this).crud("PUT", "/api/teccam/dark", dark)
})

$("#set-tint").click(function(e){
    e.preventDefault()
    var freq = $("#tint").val()
    $(this).crud("PUT", "/api/teccam/exptime", freq)
})

$("#create-gain").click(function(e){
    e.preventDefault()
    var gain_type = $("#gain-type").val()
    var centroid_size = $("#centroid-size").val()
    $(this).crud("POST", "/api/teccam/gain", [gain_type, centroid_size])
})

$("#load-gain").click(function(e){
    e.preventDefault()
    var gain = $("#gain-list").val()
    $(this).crud("PUT", "/api/teccam/gain", gain)
})

$("#cred-patrol").click(function(e){
    e.preventDefault()
    $(this).crud("POST", "/api/teccam/patrol")
})

$("#cred-small").click(function(e){
    e.preventDefault()
    $(this).crud("DELETE", "/api/teccam/patrol")
})

$("#set-temperature").click(function(e){
    e.preventDefault()
    var temp = $("#temperature").val()
    $(this).crud("PUT", "/api/teccam/temperature", temp)
})
