'use strict';
var utils = require('../lib/utils'),
    mediaquery = require('css-mediaquery');
/*
    Routes for /start/ could be any of the following:
    * `/start/`
    * `/start/?cols=6&med=48em&lrg=60em`
    * `/start/?cols=6&sm=screen and (min-device-width: 480px)`
*/
module.exports = function (req, res, next) {

    var query = utils.extend({}, req.query),
        mq = hasMQ(query);

    //if we have columns, then normalize them into an array.
    if (query.cols) {
        query.cols = normalizeCols(query.cols);
    }

    if (mq) {
        Object.keys(mq).forEach(function (key) {
            var validMqStr = isValidMQ(mq[key]);
            if (!validMqStr) {
                //remove the media query from `query` if it's not valid.
                delete query[key];
            }
            else {
                //update the media query in `query` with the legitimate one.
                query[key] = validMqStr;
            }
        });
    }

    res.expose(query, 'app.start.query');
    res.render('start');
};

// Takes in a string input for number of columns and converts it into an array.
function normalizeCols (cols) {
    //cols will always be a string, so we can convert the string to an array of 1 or more integers.
    return cols.split(",").map(function (x) {
        return parseInt(x);
    });
}


/*
Checks to see if media queries are valid, by following these steps:
    Does the query param value parse as a media query?
        If yes? return true.
        If not, then assume it's a width value, so wrap it with "screen and (min-width: " + value + ")"
    Does it now parse as a media query?
        If yes, return true.
        If not, return false.
*/
function isValidMQ (mqStr) {
    //This regex splits up a string that contains a sequences of letters or numbers ("48em", "480px") into an array of grouped letters and numbers (["48", "em"], ["480", "px"])
    var RE_SEPARATE_NUM_LETTERS = /[a-zA-Z]+|[0-9]+/g,
        captures;
    try {
        mediaquery.parse(mqStr);
    } catch (e) {
        //invalid media query, so let's check that there's some floated value in here, and if there is, we will prepend/append some strings
        captures = mqStr.match(RE_SEPARATE_NUM_LETTERS);
        if (captures.length === 2 && parseFloat(captures[0])) {
            mqStr = 'screen and (min-width: ' + mqStr + ')';
        }

        else {
            return false;
        }
        try {
            mediaquery.parse(mqStr);
        } catch (e) {
            //still not a valid media query
            return false;
        }
    }

    return mqStr;
}

function hasMQ (obj) {
    var o = utils.extend({}, obj);
    delete o.cols;
    delete o.fonts;
    delete o.prefix;
    if (Object.getOwnPropertyNames(o).length === 0) {
        return false;
    }
    return o;
}

@@ -330,16 +330,31 @@
 query = 
+normalizeQuery(
 utils.ex
@@ -376,34 +376,8 @@
 ery)
-,%0A        mq = hasMQ(query
 );%0A%0A
@@ -455,24 +455,24 @@
 ery.cols) %7B%0A
+
         quer
@@ -518,443 +518,8 @@
  %7D%0A%0A
-    if (mq) %7B%0A        Object.keys(mq).forEach(function (key) %7B%0A            var validMqStr = isValidMQ(mq%5Bkey%5D);%0A            if (!validMqStr) %7B%0A                //remove the media query from %60query%60 if it's not valid.%0A                delete query%5Bkey%5D;%0A            %7D%0A            else %7B%0A                //update the media query in %60query%60 with the legitimate one.%0A                query%5Bkey%5D = validMqStr;%0A            %7D%0A        %7D);%0A    %7D%0A%0A
     
@@ -2153,40 +2153,288 @@
 %0A%7D%0A%0A
-function hasMQ (obj) %7B%0A    var o
+/*%0A    This function takes in a %60req.query%60 object, validates all the media queries within it, removes the incorrect media queries, and then returns a modified %60req.query%60 object, with only valid values within in.%0A*/%0Afunction normalizeQuery (obj) %7B%0A    var query = obj,%0A        mq
  = u
@@ -2449,19 +2449,21 @@
 end(%7B%7D, 
-obj
+query
 );%0A    d
@@ -2468,17 +2468,18 @@
  delete 
-o
+mq
 .cols;%0A 
@@ -2488,17 +2488,18 @@
  delete 
-o
+mq
 .fonts;%0A
@@ -2509,17 +2509,18 @@
  delete 
-o
+mq
 .prefix;
@@ -2524,59 +2524,248 @@
 ix;%0A
+%0A
     
-if (
 Object.
-getOwnPropertyNames(o).length === 0)
+keys(mq).forEach(function (key) %7B%0A        var validMqStr = isValidMQ(mq%5Bkey%5D);%0A        if (!validMqStr) %7B%0A            //remove the media query from %60query%60 if it's not valid.%0A            delete query%5Bkey%5D;%0A        %7D%0A        else
  %7B%0A 
@@ -2775,28 +2775,129 @@
     
+ 
-return false
+   //update the media query in %60query%60 with the legitimate one.%0A            query%5Bkey%5D = validMqStr
 ;%0A
+    
     %7D%0A
+    %7D);%0A%0A
     
@@ -2903,13 +2903,17 @@
  return 
-o
+query
 ;%0A%7D%0A

replace `hasMQ()` with `normalizeQuery()`