export { onAcidClick,
     onAcidMouseOver,
     onAcidMouseLeave,

     callbacks
      };

class Selection {

    constructor(protein, from, to){
        this.protein = protein,
        this.from = from,
        this.to = to
    }

    contains(protein, acid){
        if(this.protein != protein ){
            return false;
        }
        if(this.to == null){
            return acid == this.from
        }
        return this.from <= acid && acid <= this.to;
    }


}

let selected = {};
let previewing = {};

let endSelectionButton = $("#cancel-selection");

let callbacks = {
    firstSelection: [() => {endSelectionButton.show()}],
    finalizedSelection: [],
    previewChange: [],
    cancelSelection: []
}

endSelectionButton.on('click', function(){
    fireCallbacks(callbacks.cancelSelection, selected);
    selected = new Selection();
    endSelectionButton.hide();
});


initSelectionObjects();


function initSelectionObjects() {
    selected = new Selection();
    previewing = new Selection();
}



function select(protein, acid) {
    //nothing selected yet
    if (selected.from == null) {
        selected.protein = protein;
        selected.from = acid;
        fireCallbacks(callbacks.firstSelection, selected);
        return false;
    }

    //we selected from a different protein, does not make sense
    if (selected.protein != protein) {
        return false
    }

    selected.to = acid;

    //if in bad order, flip
    if (selected.from > selected.to) {
        [selected.from, selected.to] = [selected.to, selected.from]
    }
    return true;
}


function onAcidClick( protein, acid) {
    //TODO: sync views? vue maybe? just events? 
    if(select(protein, acid)){
        fireCallbacks(callbacks.finalizedSelection, selected);
        initSelectionObjects();
        return true;
    }
    return false;
}


function onAcidMouseOver(protein, acid) {
    if (selected.from == null || selected.protein != protein) {
        return false;
    }
    previewing = new Selection(selected.protein, select.from, acid);

    //if in bad order, flip
    if (previewing.from > previewing.to) {
        [previewing.from, previewing.to] = [previewing.to, previewing.from]
    }
    fireCallbacks(callbacks.previewChange, previewing);
}

function onAcidMouseLeave(protein, acid){
    previewing = new Selection();
    fireCallbacks(callbacks.previewChange, previewing);
}


function fireCallbacks(callbacks, selection) {
    for (let cb of callbacks) {
        cb(selection);
    }
}

