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 Iconv       = require('iconv').Iconv;
var config      = require('../../config');


var mockup_id = config.idcard.mockup_id;
var photo_mockup_id = mockup_id;

router.use('/photo', express.static(path.normalize(__dirname + '/../../output/idcard')));

router.get('/', function(req, res) {
  res.send({status:true});
});
router.get('/readers', function(req, res) {
  if (config.idcard.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});
  }
});

router.get('/read/:reader?', function(req, res) {
  if (config.idcard.mockup) {
    setTimeout(function() {
      res.charset='UTF-8';
      res.send({
        status:true,
        idcard:config.idcard.cards[mockup_id]
      });
      photo_mockup_id = mockup_id;
      mockup_id = (mockup_id+1)%config.idcard.cards.length;
    }, 1000);
    return;
  }
  try {
    var idcard = {};
    var iconv = new Iconv('tis-620', 'utf-8');
    pcsc.init();
    var reader = selectReader(req.params.reader || '');
    if (reader==null) {
      throw new Error('no reader not found.');
    }
    pcsc.select_reader(reader);
    var atr = pcsc.connect();
    console.log('atr : ' + atr.toString('hex').toUpperCase());

    // CMD_SELECT
    input = new Buffer('00A4040008A000000054480001', 'hex');
    result = pcsc.sendapdu(input);
    console.log(result);


    // CMD_NATIONID
    input = new Buffer('80b0000402000d', 'hex');
    result = pcsc.sendapdu(input);
    console.log(result);
    console.log(result.resp.toString());
    idcard.nationid = result.resp.toString();
    //
    //
    // CMD_PERSIONINFO
    input = new Buffer('80b000110200d1', 'hex');
    result = pcsc.sendapdu(input);
    console.log(result);
    var info = iconv.convert(result.resp).toString();
    console.log(info);
    var infoTH = info.substr(0, 100).split('#').map(function(item){return item.trim()});
    var infoEN = info.substr(100, 100).split('#').map(function(item){return item.trim()});
    var birth = (parseInt(info.substr(200,4))-543) + '-'
        + info.substr(204,2) + '-' + info.substr(206,2);
    var gender = info.substr(208,1)=='1' ? 'M' : 'F';
    console.log(infoTH, infoEN, birth, gender);

    idcard.prenameTH = infoTH[0];
    idcard.firstnameTH = infoTH[1];
    idcard.lastnameTH = infoTH[3];
    idcard.prenameEN = infoEN[0];
    idcard.firstnameEN = infoEN[1];
    idcard.lastnameEN = infoEN[3];
    idcard.birth = birth;
    idcard.gender = gender;

    // CMD_ADDRESS
    input = new Buffer('80b01579020064', 'hex');
    result = pcsc.sendapdu(input);
    console.log(result);
    var tmp = iconv.convert(result.resp).toString();
    console.log(tmp);
    var tmp2 = tmp.split('#').map(function(item){return item.trim()});
    var addr = {
      houseNo: tmp2[0],
      villageNo: tmp2[1],
      lane: tmp2[2],
      road: tmp2[3],
      unknown: tmp2[4],
      tambon: tmp2[5],
      amphur: tmp2[6],
      province: tmp2[7]
    };
    console.log(addr);

    idcard.address = addr;

    // CMD_ISSUE_EXPIRE
    input = new Buffer('80b00167020012', 'hex');
    result = pcsc.sendapdu(input);
    console.log(result);
    var tmp = result.resp.toString();
    console.log(tmp);
    var issue = (parseInt(tmp.substr(0,4))-543) + '-'
        + tmp.substr(4,2) + '-' + tmp.substr(6,2);
    var expire = (parseInt(tmp.substr(8,4))-543) + '-'
        + tmp.substr(12,2) + '-' + tmp.substr(14,2);
    console.log(issue, expire);

    idcard.issueDate = issue;
    idcard.expireDate = expire;

    res.charset='UTF-8';
    res.send({
      status:true,
      idcard:idcard
    });

  } catch (e) {
    console.log(e);
    res.charset='UTF-8';
    res.send({status:false});
  }
});

router.get('/readPhoto/:reader?', function(req, res) {
  if (config.idcard.mockup) {
    setTimeout(function() {
      res.send({
        status:true,
        nationid:config.idcard.cards[photo_mockup_id].nationid
      })
    }, 5000);
    return;
  }
  try {
    pcsc.init();
    var reader = selectReader(req.params.reader || '');
    if (reader==null) {
      throw new Error('no reader not found.');
    }
    pcsc.select_reader(reader);
    var atr = pcsc.connect();

    // CMD_SELECT
    input = new Buffer('00A4040008A000000054480001', 'hex');
    result = pcsc.sendapdu(input);

    // CMD_NATIONID
    input = new Buffer('80b0000402000d', 'hex');
    result = pcsc.sendapdu(input);
    var nationid = result.resp.toString();

    //photo
    var cmd = [];
    for (i = 0; i < 21; i++) {
      var xof = i * 254 + 379;
      var xwd = i==20 ? 38 : 254;
      var sp2 = (xof >> 8) & 0xff;
      var sp3 = xof & 0xff;
      var sp6 = xwd & 0xff;
      cmd.push(new Buffer([0x80, 0xb0, sp2, sp3, 0x02, 0x00, sp6]));
    }

//    var photoBuffer = new Buffer(5118);
    var photoBuffer;
    var fs = require('fs');
    var wstream = fs.createWriteStream(path.normalize(__dirname + '/../../output/idcard') + '/' + nationid + '.jpg');

//    var offset = 0;
    for (var i = 0; i < cmd.length; i++) {
      var result = pcsc.sendapdu(cmd[i]);
      photoBuffer = new Buffer(i==20 ? 38 : 254);
      result.resp.copy(photoBuffer, 0, 0, i==20 ? 38 : 254);
      wstream.write(photoBuffer);
//      result.resp.copy(photoBuffer, offset, 0, i==20 ? 38 : 254);
//      offset += 254;
    }
    wstream.end();
    wstream.on('finish', function() {
      res.send({
        status:true,
        nationid:nationid
      });
    });

    wstream.on('error', function() {
      res.send({
        status:false,
        nationid:nationid
      });
    });
  } catch (e) {
    console.log(e);
    res.charset='UTF-8';
    res.send({status:false});
  }
});

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;
