'use strict';

var _ = require('./underscore_ext');
var unicode = require('./unicode_utils');
var chromInfo = require('./chromInfo');
var centromere = require('./centromere');

var toInt = x => parseInt(x, 10);
var clip = (len, x) => x < 1 ? 1 : (x > len ? len : x);
var M = 1000 * 1000;

module.exports = function (text, assembly) {
	// strip spaces, cvt to lower, match chr1:2-chr3:4 format
	text = unicode.normalize(text).replace(/ /g, '').toLowerCase();
	var pos = text.match(/^(chr[0-9xyXY]+)([pq]?)(:([0-9,]+)-([0-9,]+))?$/);
	if (pos) {
		let chrom = pos[1].replace(/x/, 'X').replace(/y/, 'Y'),
			cm = _.getIn(centromere, [assembly, chrom]),
			maxEnd = _.getIn(chromInfo, [assembly, chrom], 250 * M),
			baseStart, baseEnd;

		if (pos[3] !== undefined) {
			baseEnd = clip(maxEnd, toInt(pos[5].replace(/,/g, '')));
			baseStart = clip(baseEnd, toInt(pos[4].replace(/,/g, '')));
		} else if (cm && pos[2] === 'p') {
			baseStart = 1;
			baseEnd = cm - 1;
		} else if (cm && pos[2] === 'q') {
			baseStart = cm;
			baseEnd = maxEnd;
		} else {
			baseStart = 1;
			baseEnd = maxEnd;
		}
		return {chrom, baseStart, baseEnd};
	}
};

@@ -508,16 +508,17 @@
 %5B0-9,%5D+)
+(
 -(%5B0-9,%5D
@@ -518,17 +518,20 @@
 (%5B0-9,%5D+
-)
+?))?
 )?$/);%0A%09
@@ -772,19 +772,21 @@
 base
-End
+Start
  = clip(
 maxE
@@ -781,19 +781,20 @@
  = clip(
-max
+base
 End, toI
@@ -800,17 +800,17 @@
 Int(pos%5B
-5
+4
 %5D.replac
@@ -827,37 +827,91 @@
 )));%0A%09%09%09base
-Start
+End = baseStart;%0A%09%09%09if (pos%5B6%5D !== undefined) %7B%0A%09%09%09%09baseEnd
  = clip(
 baseEnd, toI
@@ -890,36 +890,35 @@
 %09baseEnd = clip(
-base
+max
 End, toInt(pos%5B4
@@ -908,33 +908,33 @@
 xEnd, toInt(pos%5B
-4
+6
 %5D.replace(/,/g, 
@@ -940,16 +940,21 @@
  '')));%0A
+%09%09%09%7D%0A
 %09%09%7D else

allow query like chr17:7,578,460, which has only a single basepair