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


// 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, 'picture.jpeg', 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, 'picture.jpeg', 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, 'picture.jpeg', {encoding: null}, function(data){
		console.log(data);
		res.contentType('image/jpeg');
		let buffer = new Buffer.from(data);
		res.send(buffer);
	    });
});


module.exports = router;
