var express     = require('express');
var path        = require('path');
var bodyParser  = require('body-parser');
var q           = require('q');
var router      = express.Router();
var pcsc        = require('pcsc');
var config      = require('../../config');

router.get('/', function(req, res) {
  res.send({status:true});
});
router.get('/readers', function(req, res) {
  if (config.rfid.mockup) {
    res.send({status:true, readers:['DUMMY READER']});
    return;
  }

  try {
    pcsc.init();
    var readers = pcsc.get_reader_list();
    res.send({status:true, readers:readers});
  } catch (e) {
    res.send({status:false, error:e});
  }
});

router.get('/read/:reader?', function(req, res) {
  if (config.rfid.mockup) {
    res.send({
      status:true,
      cardId:config.rfid.cards[config.rfid.mockup_id]
    });
    return;
  }
  try {
    pcsc.init();
    var reader = selectReader(req.params.reader || '');
    if (reader==null) {
      throw 'no reader not found.';
    }
    pcsc.select_reader(reader);
    var atr = pcsc.connect();
    input = new Buffer('FFCA000000', 'hex');
    result = pcsc.sendapdu(input);

//    console.log('atr : ' + atr.toString('hex').toUpperCase());

    res.send({
      status:true,
      cardId:result.resp.toString('hex').toUpperCase()
    });
  } catch(e) {
    res.send({status:false, error:e});
  }
});

var selectReader = function(targetReader) {
  var readers = pcsc.get_reader_list();
  var reader = null;

  if (targetReader != '') {
    for (var i = 0; i < readers.length; i++) {
      if (readers[i]==req.body.reader) {
        reader = readers[i];
        break;
      }
    }
  }
  if (reader==null) {
    for (var i = 0; i < readers.length; i++) {
      if (readers[i].toLowerCase().indexOf("smartcard")) {
        reader = readers[i];
        break;
      }
    }
  }
  if (reader==null) {
    reader = readers[i];
  }
  return reader;
}

module.exports = router;
