/**
    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you under the Apache License, Version 2.0 (the
    "License"); you may not use this file except in compliance
    with the License.  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing,
    software distributed under the License is distributed on an
    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    KIND, either express or implied.  See the License for the
    specific language governing permissions and limitations
    under the License.
*/
var cordova_util = require('./util'),
    path = require('path'),
    shell = require('shelljs'),
    platforms     = require('../platforms'),
    config_parser = require('./config_parser'),
    fs = require('fs'),
    util = require('util'),
    http = require("http"),
    url = require("url"),
    mime = require("mime"),
    zlib = require("zlib");

function launchServer(projectRoot, port) {
    var server = http.createServer(function(request, response) {
        var urlPath = url.parse(request.url).pathname;
        var firstSegment = /\/(.*?)\//.exec(urlPath);
        if (!firstSegment) {
            response.writeHead(404, {"Content-Type": "text/plain"});
            response.write("404 Not Found\nPlease use URLs in the form /$platformId/www/...");
            response.end();
            return;
        }
        var platformId = firstSegment[1];
        // Strip the platform out of the path.
        urlPath = urlPath.slice(platformId.length + 1);

        var parser = new platforms[platformId].parser(path.join(projectRoot, 'platforms', platformId));
        var filePath = null;

        if (urlPath == '/config.xml') {
            filePath = parser.config_xml();
        } else if (urlPath == '/project.json') {
            processAddRequest(request, response, platformId, projectRoot);
            return;
        } else if (/^\/www\//.test(urlPath)) {
            filePath = path.join(parser.www_dir(), urlPath.slice(5));
        } else {
            response.writeHead(404, {"Content-Type": "text/plain"});
            response.write("404 Not Found\n");
            response.end();
            return;
        }

        fs.exists(filePath, function(exists) {
            if (exists) {
                if (fs.statSync(filePath).isDirectory()) {
                    response.writeHead(200, {"Content-Type": "text/plain"});
                    response.write("TODO: show a directory listing.\n");
                    response.end();
                } else {
                    var mimeType = mime.lookup(filePath);
                    var respHeaders = {
                      'Content-Type': mimeType
                    };
                    var readStream = fs.createReadStream(filePath);

                    var acceptEncoding = request.headers['accept-encoding'] || '';
                    if (acceptEncoding.match(/\bdeflate\b/)) {
                        respHeaders['content-encoding'] = 'deflate';
                        readStream = readStream.pipe(zlib.createDeflate());
                    } else if (acceptEncoding.match(/\bgzip\b/)) {
                        respHeaders['content-encoding'] = 'gzip';
                        readStream = readStream.pipe(zlib.createGzip());
                    }
                    response.writeHead(200, respHeaders);
                    readStream.pipe(response);
                }
            } else {
                response.writeHead(404, {"Content-Type": "text/plain"});
                response.write("404 Not Found\n");
                response.end();
            }
        });

    }).listen(port);

    console.log("Static file server running at\n  => http://0.0.0.0:" + port + "/\nCTRL + C to shutdown");
    return server;
}

function processAddRequest(request, response, platformId, projectRoot) {
    var parser = new platforms[platformId].parser(path.join(projectRoot, 'platforms', platformId));
    var wwwDir = parser.www_dir();
    var payload = {
        'configPath': '/' + platformId + '/config.xml',
        'wwwPath': '/' + platformId + '/www',
        'wwwFileList': shell.find(wwwDir)
            .filter(function(a) { return !fs.statSync(a).isDirectory(); })
            .map(function(a) { return a.slice(wwwDir.length); })
    };
    response.writeHead(200, {
        'Content-Type': 'application/json',
        'Cache-Control': 'no-cache'
    });
    response.write(JSON.stringify(payload));
    response.end();
}

module.exports = function server(port) {
    var projectRoot = cordova_util.isCordova(process.cwd());
    port = +port || 8000;

    if (!projectRoot) {
        throw new Error('Current working directory is not a Cordova-based project.');
    }

    // Return for testing.
    return launchServer(projectRoot, port);
};


@@ -1283,329 +1283,318 @@
     
-var urlPath = url.parse(request.url).pathname;%0A        var firstSegment = /%5C/(.*?)%5C//.exec(urlPath);%0A        if (!firstSegment) %7B%0A            response.writeHead(404, %7B%22Content-Type%22: %22text/plain%22%7D);%0A            response.write(%22404 Not Found%5CnPlease use URLs in the form /$platformId/www/...%22);%0A            response.end();
+function do404() %7B%0A            response.writeHead(404, %7B%22Content-Type%22: %22text/plain%22%7D);%0A            response.write(%22404 Not Found%5Cn%22);%0A            response.end();%0A        %7D%0A        var urlPath = url.parse(request.url).pathname;%0A        var firstSegment = /%5C/(.*?)%5C//.exec(urlPath);%0A        if (!firstSegment) %7B
 %0A   
@@ -1600,32 +1600,40 @@
           return
+ do404()
 ;%0A        %7D%0A    
@@ -1670,16 +1670,92 @@
 ent%5B1%5D;%0A
+        if (!platforms%5BplatformId%5D) %7B%0A            return do404();%0A        %7D%0A
         
@@ -2364,156 +2364,20 @@
   re
-sponse.writeHead(404, %7B%22Content-Type%22: %22text/plain%22%7D);%0A            response.write(%22404 Not Found%5Cn%22);%0A            response.end();%0A            return
+turn do404()
 ;%0A  
@@ -3650,142 +3650,18 @@
   re
-sponse.writeHead(404, %7B%22Content-Type%22: %22text/plain%22%7D);%0A                response.write(%22404 Not Found%5Cn%22);%0A                response.end
+turn do404
 ();%0A

Fix a crash on undefined platform in path.