var loopDetail = d3.select("#loopDetail").append("svg")
                                    .attr("width", width-20)
                                    .attr("height", 300);   

function drawBfactorForDetail(n, height, start, length, firstAA, canvasLength){

	var fluctationValues = [];
    let numOfAtoms = 0;
    for (var i = 0; i < atomsFromPdb[n].length; i++) {
    	if(parseInt(atomsFromPdb[n][i][5]) >= firstAA && parseInt(atomsFromPdb[n][i][5]) < firstAA + length) {
    		fluctationValues[numOfAtoms] = atomsFromPdb[n][i][10];
    		numOfAtoms++;
    	}	
    }

    let bfactPoins = [start + " " + height + ", "];
    let svgHeight = 30;

    let thisLoopElementWidth = (canvasLength / numOfAtoms);

    for (var i = 0; i < numOfAtoms; i++) {

		thisBfactNorm = (fluctationValues[i] - lowestBfact)/(highestBfact-lowestBfact);
		var calcHeight = height - svgHeight * thisBfactNorm - 5;
		if(isNaN(calcHeight)) calcHeight = height;
		bfactPoins += [start + i*thisLoopElementWidth + " " + calcHeight + ", "];
    }

    bfactPoins += [start + numOfAtoms*thisLoopElementWidth + " " + height];
    // console.log(fluctationValues)

    loopDetail.append("polygon")
        .attr("fill", "grey")
        .attr("opacity", 0.3)
        .attr("points", bfactPoins);
	return;
}

function drawLoopsDetails(){

	var loopsDetailYpos = -1;

	for (var index = 0; index < highlighted.length; index++) {
		objectIndex = -1;
		if(highlighted[index].size > 0) loopsDetailYpos++;
		highlighted[index].forEach(function(object) {

			objectIndex++;
              
			let seqBegin = object.start;
			let seqEnd = object.end;
			let seqIndex = object.index;
			let loopHeight = 75*loopsDetailYpos + 40;
			var widthLoop = 3; //widthLoop (resp height) of the coil line
			let thisElementWidth = ((loopDetail.attr('width') * 0.8 /highlighted[index].size))/(seqEnd-seqBegin) * 0.9;
			let n = index;

			// console.log(object.start + '   ' + object.end + '   ' + thisElementWidth + '   ' + (loopDetail.attr('width') + '   ' + highlighted[index].size)+'   '+(seqEnd-seqBegin));

			var globalI = objectIndex * (loopDetail.attr('width') * 0.9 /highlighted[index].size);

			// console.log('seqBeg: ',seqBegin,seqEnd);
			var thisLoopDetail = loopDetail.append('g');

			drawDetailedLoop(thisLoopDetail, seqBegin, seqEnd, n, thisElementWidth, globalI, loopHeight, widthLoop);

			let zkurvenaLength = thisLoopDetail.node().getBBox().width - 6;
			drawBfactorForDetail(n, loopHeight, globalI+xoffset, seqEnd - seqBegin, seqBegin, zkurvenaLength);
			thisLoopDetail.remove();
			drawGeometryInfo(loopDetail, loopHeight, globalI+xoffset, zkurvenaLength, n, seqIndex);
			drawDetailedLoop(loopDetail, seqBegin, seqEnd, n, thisElementWidth, globalI, loopHeight, widthLoop);

			// let circleRadius = zkurvenaLength/15;
			// loopDetail.append('circle')
			// 				.attr('cx', globalI + xoffset + zkurvenaLength + circleRadius)
			// 				.attr('cy', loopHeight)
			// 				.attr('r', circleRadius)
			// 				.attr('fill', 'red');
		});
	} 
}

function getLetter(le){
	// console.log(String.fromCharCode('a'.charCodeAt(0) + Math.round(parseFloat(le)*6)))
	return String.fromCharCode('a'.charCodeAt(0) + Math.floor((0.999-parseFloat(le))*6));
}

function drawGeometryInfo(group, loopHeight, start, length, n, seqIndex){
	var geomSymbols = ['D', '\u03B4', '\u03B8', '\u03C1'];
	var geomValues = [parseFloat(loops[n][seqIndex].distance).toFixed(2),
					  parseFloat(loops[n][seqIndex].delta).toFixed(2),
					  parseFloat(loops[n][seqIndex].theta).toFixed(2),
					  parseFloat(loops[n][seqIndex].rho).toFixed(2)];
	var geomPoss = [parseFloat(loops[n][seqIndex].distance_pos).toFixed(2),
					  parseFloat(loops[n][seqIndex].delta_pos).toFixed(2),
					  parseFloat(loops[n][seqIndex].theta_pos).toFixed(2),
					  parseFloat(loops[n][seqIndex].rho_pos).toFixed(2)];
	for (let index = 0; index < geomSymbols.length; index++) {
		group.append('rect')
				.attr('height', 25)
				.attr('width', (index==3) ? length/4 : length/4+1)
				.attr('fill', '#' + getLetter(geomPoss[index]) + '3' 
								  + getLetter(geomPoss[index]) + '3' 
								  + getLetter(geomPoss[index]) + '3')
				.attr('x', start+index*length/4)
				.attr('y', loopHeight);
		let geoOfset = length/120;
		if(length/4 > 50) {
			loopDetail.append('text')
			    .attr("x", geoOfset+start+index*length/4)
			    .attr("y", loopHeight + 22)
			    .attr('class', (geomPoss[index]>0.6) ? 'myLabel_white' : 'myLabel')
			    .style("font-weight", 'bold')
			    .text(geomSymbols[index]);
			geoOfset += 10;
		}
		if(length/4 < 40) {
			for (var i = 0; i < geomValues.length; i++) {
				geomValues[i] = parseInt(geomValues[i]);
			}
		}
		loopDetail.append('text')
			    .attr("x", geoOfset+start+index*length/4)
			    .attr("y", loopHeight + 22)
			    .attr('class', (geomPoss[index]>0.6) ? 'myLabel_white' : 'myLabel')
			    .style("font-weight", 'thin')
			    .text(geomValues[index]);
		// geomSymbols[index]
	}
}

function drawDetailedLoop(group, seqBegin, seqEnd, n, thisElementWidth, globalI, loopHeight, widthLoop){

	var yOffset = (thisElementWidth+9 > 20) ? 12 : thisElementWidth+4;
	let lastGlobalI = 0;

	group.append("text")
          .attr("y", loopHeight - yOffset)
          .attr("x", globalI+xoffset)
          .attr("fill", colorMolecule[n])
          .style("font-size", "12px")
          .text(seqBegin);

	for (i = seqBegin; i < seqEnd; i++){
	    // console.log(i);
	    // console.log('loopDetail: \n',ss,'\n',n,'\n',i);
	    var thisSS = ss[n][i];
	    
	    var start = i;
	    
	    while (ss[n][i+1] === thisSS && i < seqEnd)i++;
	    var gap = i - start + 1;

	    if (thisSS === 'E') drawJuxtaArrow(group, n, i, thisElementWidth, globalI, gap, loopHeight, loopHeight, colorMolecule[n]);
	    if (thisSS === 'H') drawJuxtaHelix(group, n, i, thisElementWidth, globalI, gap, loopHeight, loopHeight, colorMolecule[n]);
	    if (thisSS === 'C') drawJuxtaRect(group, thisElementWidth, globalI,  gap, loopHeight, loopHeight, widthLoop, colorMolecule[n]);
	    
	    globalI += Math.round( gap * thisElementWidth);

	    if(i!=seqBegin) textIndex = group.append("text")
	                      .attr("y", loopHeight - yOffset)
	                      .attr("x", globalI+xoffset)
	                      .attr('text-anchor', 'central')
	                      .attr("fill", colorMolecule[n])
	                      .style("font-size", "12px")
	                      .text(i)
	                      .attr("transform", "translate (-" + (i.toString().length * 3.34) + ", 0)" );

        lastGlobalI = globalI;
	} 
}