var options = {
  width: 500,
  height: 500,
  //antialias: true,
  quality : 'high',
  background : 'white'
}
options.width = document.getElementById("pv-panel").clientWidth;
options.height = document.getElementById("pv-panel").clientWidth * 3/4;

var colorMolecule = ['#1f77b4', '#ff7f0e', '#2ca02c', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf', '#6b6ecf', '#8ca252', '#bd9e39', '#e7ba52','#d6616b', '#a55194'];

var viewer = pv.Viewer(document.getElementById('pv-panel'), options);
var thisStructure;

function loadMolecule(name, index) {
  // asynchronously load the PDB file for the dengue methyl transferase
  // from the server and display it in the viewer.
  pv.io.fetchPdb('./public/uploads/'+ name, function(structure) {

  	thisStructure = structure;
  	
  	//save ss elements into the structure
	var s = [];
	structure._j[0]._q.forEach(function(element) {
		s.push(element._cR);
	});
	ss[index]=s;

  	//save amino acids into the structure
	s = [];
	structure._j[0]._q.forEach(function(element) {
		s.push(element._L);
	});
	aminoAcids[index]=s;	

	//push atoms for highlighting
	atoms[index] = [];
	var lastPos = -1;
	for (var i = 0; i < structure.atoms().length; i++) {
		if(structure.atoms()[i]._t._cu !== lastPos) {
			lastPos++;
			atoms[index][lastPos] = structure.atoms()[i];
		}
		
	}

	// display the protein as cartoon, coloring the secondary structure
	// elements in a rainbow gradient.
	viewer.cartoon(proteins[index], structure, { color : color.uniform(rgb.hex2rgb(colorMolecule[index])) });
	viewer.centerOn(structure);
	viewer.autoZoom();
  });
}

/**
 * Adds a listener for mouse over events
 * @see {@link http://pv.readthedocs.org/en/v1.8.1/sample-hover.html}
 *
 * @param {object} viewer
 */
function setMouseMove(viewer){
	
	// variable to store the previously picked atom. Required for resetting the color
	// whenever the mouse moves.
	var prevPicked = null;
	// add mouse move event listener to the div element containing the viewer. Whenever
	// the mouse moves, use viewer.pick() to get the current atom under the cursor.
	parent.addEventListener('mousemove', function(event) {
	    var rect = viewer.boundingClientRect();
	    var picked = viewer.pick({ x : event.clientX - rect.left,
	                               y : event.clientY - rect.top });
	    //console.log((event.clientX - rect.left) + "  " + (event.clientY - rect.top));
	    if (prevPicked !== null && picked !== null &&
	        picked.target() === prevPicked.atom) {
	      return;
	    }
	    if (prevPicked !== null) {
	      // reset color of previously picked atom.
	      setColorForAtom(prevPicked.node, prevPicked.atom, prevPicked.color);
	    }
	    if (picked !== null) {
	      var atom = picked.target();
	      var s = "Sequence: " + picked._d6._L;
	      s += ", Residue: " + atom.qualifiedName().substring(2, 5);
	      s += ", On position: " + picked._dQ._t._d5;
	      console.log();
	      $("#toBeAligned").val(s);
	      // get RGBA color and store in the color array, so we know what it was
	      // before changing it to the highlight color.
	      var color = [0,0,0,0];
	      picked.node().getColorForAtom(atom, color);
	      prevPicked = { atom : atom, color : color, node : picked.node() };

	      setColorForAtom(picked.node(), atom, 'red');
	    } else {
	      //document.getElementById('picked-atom-name').innerHTML = '&nbsp;';
	      $("#toBeAligned").val(displayedMessage);
	      prevPicked = null;
	    }
	    viewer.requestRedraw();
	});

	function setColorForAtom(go, atom, color) {
	    var view = go.structure().createEmptyView();
	    view.addAtom(atom);
	    go.colorBy(pv.color.uniform(color), view);
	}
}

function setMouseClick(viewer){

	var prev = null;

	viewer.on('doubleClick', function(picked) {
		viewer.centerOn(thisStructure);
		// viewer.setCenter(picked.pos(), 500);
		// viewer.autoZoom();
		// return;
	});

	viewer.on('click', function(picked, ev) {
		if (picked === null || picked.target() === null) {			
			return;
		}
		// don't to anything if the clicked structure does not have an atom
		if (picked.node().structure === undefined) {
			return;
		}
		
		// when the shift key is pressed, extend the selection, otherwise
		// only select the clicked atom.
		var extendSelection = ev.shiftKey;
		var sel;

		if (extendSelection) {
			var sel = picked.node().selection();
		} else {
			var sel = picked.node().structure().createEmptyView();
		}		

		// in case atom was not part of the view, we have to add it, because
		// it wasn't selected before. Otherwise removeAtom took care of it
		// and we don't have to do anything.


		if(prev === picked.target()) {
			var pos = proteins.findIndex(i => i === picked._d6._L);
			highlighted[pos] = 9999;

			sel = picked.node().structure().createEmptyView();
			picked.node().setSelection(sel);
			prev = null;
			
			redrawD3();
		} else {
			if (!sel.removeAtom(picked.target(), true)) {
				sel.addAtom(picked.target());
				prev = picked.target();
			}

			var chainIndex = proteins.findIndex(i => i === picked._d6._L);
			var residueIndex = parseInt([Object.keys(sel._j[0]._by)[0]]);
			var residueIndexDown = residueIndex;

			var thisSS = ss[chainIndex][residueIndex];
			if(thisSS !== 'H' && thisSS !== 'E') return;
			highlighted[chainIndex] = notAlignToAlign[chainIndex][residueIndex];
			while(ss[chainIndex][++residueIndex] === thisSS) sel.addAtom(atoms[chainIndex][residueIndex]);
			while(ss[chainIndex][--residueIndexDown] === thisSS) sel.addAtom(atoms[chainIndex][residueIndexDown]);

			picked.node().setSelection(sel);
			redrawD3();
		}
		

		viewer.requestRedraw();
	});
}

//highlight viewer atom on position pos
function highlightPV(chain, pos){

	var struct = viewer.get(proteins[chain]);
	var sel = struct.selection().createEmptyView();
	sel.addAtom(atoms[chain][pos]);
	var thisSS = ss[chain][pos];
	if(thisSS !== 'H' && thisSS !== 'E') return;
	var posDown = pos;
	while(ss[chain][++pos] === thisSS) sel.addAtom(atoms[chain][pos]);
	while(ss[chain][--posDown] === thisSS) sel.addAtom(atoms[chain][posDown]);
	struct.setSelection(sel);
	viewer.requestRedraw();

}

//remove highlight selection in viewer
function resetViewerSelection(chain){
	var struct = viewer.get(proteins[chain]);
	var sel = struct.selection().createEmptyView();	
	struct.setSelection(sel);
	viewer.requestRedraw();	
}
