/**
 * httpdサーバのサンプルです。
 * ROMにある定義済みファイルの入出力と、クロスドメインRESTが確認できます。
 */
#include "boot/sketch.h"
#include "NyLPC_net.h"

#include "NyLPC_http.h"
#include "NyLPC_utils.h"
#include <stdio.h>


NyLPC_TcNet_t net;
struct MyHttpd{
	NyLPC_TcHttpd_t super;
}httpd;

#define NUM_OF_FSDATA 4
extern struct NyLPC_TRomFileData fsdata[];

static const char* ROM_PATH="rom";
static const char* SETUP_PATH="setup";
static const char* MVM_PATH="mvm";
void handler(NyLPC_TcHttpdConnection_t* i_connection)
{
	union{
		NyLPC_TcModRomFiles_t rom;
		NyLPC_TcModMiMicSetting_t setting;
		NyLPC_TcModRemoteMcu_t mvm;
	}mod;


	//SETUP
	NyLPC_cModMiMicSetting_initialize(&mod.setting,SETUP_PATH);
	if(NyLPC_cModMiMicSetting_canHandle(&mod.setting,i_connection)){
		NyLPC_cModMiMicSetting_execute(&mod.setting,i_connection);
		NyLPC_cModMiMicSetting_finalize(&mod.setting);
		return;
	}
	NyLPC_cModMiMicSetting_finalize(&mod.setting);

	//MIMICBC
	NyLPC_cModRemoteMcu_initialize(&mod.mvm,MVM_PATH);
	if(NyLPC_cModRemoteMcu_canHandle(&mod.mvm,i_connection)){
		NyLPC_cModRemoteMcu_execute(&mod.mvm,i_connection);
		NyLPC_cModRemoteMcu_finalize(&mod.mvm);
		return;
	}
	NyLPC_cModRemoteMcu_finalize(&mod.mvm);

	//ROM
	NyLPC_cModRomFiles_initialize(&mod.rom,ROM_PATH,fsdata,NUM_OF_FSDATA);
	if(NyLPC_cModRomFiles_canHandle(&mod.rom,i_connection)){
		NyLPC_cModRomFiles_execute(&mod.rom,i_connection);
		NyLPC_cModRomFiles_finalize(&mod.rom);
		return;
	}
	NyLPC_cModRomFiles_finalize(&mod.rom);

	//Redirect to index html
	NyLPC_cHttpdConnection_sendResponseHeader(
		i_connection,301,
		"text/html",
		"Status: 301:Moved Permanently\r\n"
		"Location: /rom/index.html\r\n");
	return;
}
void setup(void)
{
	//uipサービス初期化。いろいろ利用可能に。
	NyLPC_cNet_initialize(&net);
	NyLPC_cHttpd_initialize(&httpd.super,80);
	httpd.super.function.onRequest=handler;

}


void loop(void)
{
	NyLPC_TcNetConfig_t c2;
	NyLPC_cNetConfig_initialize(&c2);
	NyLPC_cNet_start(&net,&c2);
	NyLPC_cHttpd_loop(&httpd.super);
	for(;;);
}


