#!/usr/bin/env coffee
#
# Crafting Guide - serve-build
#
# Copyright (c) 2014-2015 by Redwood Labs
# All rights reserved.
#

express = require 'express'
fs      = require 'fs'
path    = require 'path'

########################################################################################################################

ROOT = './dist/'

########################################################################################################################

app = express()

app.get '*/$', (request, response)->
    response.set 'Content-Type', 'text/html'
    filePath = "#{request.path}index.html".replace /^\//, ''
    fs.stat "#{ROOT}#{filePath}", (err, stats)->
        if not err?
            response.sendFile filePath, root:ROOT
            console.log ">>> #{filePath} (for #{request.path})"
        else
            response.sendFile '/app.html', root:ROOT
            console.log ">>> app.html (for #{request.path})"

app.get '*', (request, response)->
    extension = path.extname(request.path)
    contentType = {
        '.css':  'text/css'
        '.html': 'text/html'
        '.js':   'text/javascript'
        '.json': 'application/json'
        '.map':  'application/json'
        '.png':  'image/png'
        '.ttf':  'application/octet-stream'
        '.scss': 'text/css'
    }[extension]
    console.log ">>> #{request.path}"

    response.set 'Content-Type', contentType
    response.sendFile request.path, root:ROOT

server = app.listen 8000, ->
    console.log "listening at: #{server.address().address}:#{server.address().port}"
