/**
 * React Starter Kit (https://www.reactstarterkit.com/)
 *
 * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.txt file in the root directory of this source tree.
 */

import 'babel-core/polyfill';
import path from 'path';
import express from 'express';
import React from 'react';
import ReactDOM from 'react-dom/server';
import Router from './routes';
import Html from './components/Html';
import assets from './assets';
import { port } from './config';

const server = global.server = express();

//
// Register Node.js middleware
// -----------------------------------------------------------------------------
server.use(express.static(path.join(__dirname, 'public')));

//
// Register API middleware
// -----------------------------------------------------------------------------
server.use('/api/content', require('./api/content'));

server.get('/api/v1/jobs', async (req, res, next) => {
  try{
    return res.json(
      {
        error : null,
        result : [
          {
            department : '工程研发部门',
            jobs : [
              {
                title : 'Mac开发工程师',
                numberRequired : 9
              },
              {
                title : 'IOS App测试工程师',
                numberRequired : 17
              },
              {
                title : 'Android远程控制工程师',
                numberRequired : 61
              },
              {
                title : 'Web前段工程师',
                numberRequired : 31
              },
              {
                title : 'Android多媒体软件开发工程师',
                numberRequired : 2
              }
            ]
          },
          {
            department : '产品设计部门',
            jobs : [
              {
                title : '网页设计师',
                numberRequired : 47
              },
              {
                title : 'ID/工业设计师',
                numberRequired : 39
              },
              {
                title : '视觉设计师/GUI界面设计师',
                numberRequired : 42
              },
              {
                title : '平面设计师',
                numberRequired : 8
              }
            ]
          }
        ]
      }
    );
  } catch (err) {
    next(err);
  }
});

//
// Register server-side rendering middleware
// -----------------------------------------------------------------------------
server.get('*', async (req, res, next) => {
  try {
    let statusCode = 200;
    const data = { title: '', description: '', css: '', body: '', entry: assets.main.js };
    const css = [];
    const context = {
      insertCss: styles => css.push(styles._getCss()),
      onSetTitle: value => data.title = value,
      onSetMeta: (key, value) => data[key] = value,
      onPageNotFound: () => statusCode = 404,
    };

    await Router.dispatch({ path: req.path, query: req.query, context }, (state, component) => {
      data.body = ReactDOM.renderToString(component);
      data.css = css.join('');
    });

    const html = ReactDOM.renderToStaticMarkup(<Html {...data} />);
    res.status(statusCode).send('<!doctype html>\n' + html);
  } catch (err) {
    next(err);
  }
});

//
// Launch the server
// -----------------------------------------------------------------------------
server.listen(port, () => {
  /* eslint-disable no-console */
  console.log(`The server is running at http://localhost:${port}/`);
});
