var express = require('express');
var router = express.Router();
var fs = require('fs');
var path = require('path');
var async = require('async');
require('date-utils');


// API共通ジュールのロード
var common = require('./api_common');
var manager = require('./management');


// 指定日時に一番近いファイルを取得
router.get('/:id/target', function (req, res, next) {
	console.log("Call ", req.method, req.path);
	console.log(req.params.id); 

	let dt = new Date();
	let to = dt.toFormat("YYYYMMDDHH24MISS");	// NOW
	let range = common.get_range(req);
	console.log(range);
	if (range[1] != '0') {
	    to = range[1];
	}

	let monitor_id = req.params.id;

	common.get_target(monitor_id, 'sensor.json', to, function(name){
		console.log(name);
		let r = {status: 'success', id: name};
		res.json(r);
	    });

});


// 一覧取得(装置IDと日時指定で取得)
router.get('/:id/', function (req, res, next) {
	console.log("Call ", req.method, req.path);
	console.log(req.params.id); 

	let range = common.get_range(req);
	console.log(range);

	let monitor_id = req.params.id;

	common.get_target_list(monitor_id, 'sensor.json', range[0], range[1], function(list){
		console.log(list);
		let r = {status: 'success', number: list.length, list: list};
		res.json(r);
	    });

});



// 日時を指定して、センサーデータを取り出す
router.get('/:id/:datetime/', function (req, res, next) {
	console.log("Call ", req.method, req.path);
        console.log(req.params.id);

	let datetime = req.params.datetime;
	if (datetime.length < 14) {
	    res.status(500);
	    res.send('Invalid date');
	}

	common.get_file(req, 'sensor.json', {encoding: 'utf8'}, function(data){
		console.log(data);
		try {
		    res.json(JSON.parse(data, 'utf8'));
		}
		catch(err) {
		    console.log("common.get_file: error: ", err);
		    res.status(500);
		    res.send('Invalid date');
		}
	    });
});


module.exports = router;
