// iOS 充值校验
var https = require('https');
var events = require('events');
var util = require('util');

var iOS = function(sandbox) {
  this.emitter = new events.EventEmitter(this);
  if (sandbox) {
    this.url = 'sandbox.itunes.apple.com';
  } else {
    this.url = 'buy.itunes.apple.com';
  }
}

var parse = function(emitter, status, receipt) {
  if (status != 0) {
    var message;
    if (status == 21000) {
      message = "App Store无法读取你提供的JSON数据(21000)";
    } else if (status == 21002) {
      message = "收据数据不符合格式(21002)";
    } else if (status == 21003) {
      message = "收据无法被验证(21003)";
    } else if (status == 21004) {
      message = "你提供的共享密钥和账户的共享密钥不一致(21004)";
    } else if (status == 21005) {
      message = "收据服务器当前不可用(21005)";
    } else if (status == 21006) {
      message = "收据是有效的，但订阅服务已经过期(21006)";
    } else if (status == 21007) {
      message = "收据信息是测试用（sandbox），但却被发送到产品环境中验证(21007)";
    } else if (status == 21008) {
      message = "收据信息是产品环境中使用，但却被发送到测试环境中验证(21008)";
    } else {
      message = "未知状态码(" + status + ")";
    }
    emitter.emit('error', new Error(message))
    return;
  }

  var in_app = receipt.in_app
  var length = in_app.length
  for (var i=0; i< length; ++i) {
    var order = in_app[i]
    if (order && order.product_id) {
      emitter.emit('progress', order, i, length);
    }
  }
}

iOS.prototype.verify = function(receipt) {
  var bytes = JSON.stringify({"receipt-data":receipt});
  var options = {
		hostname: this.url,
		port: 443,
		path: '/verifyReceipt',
		method: 'POST',
		headers: {
			'Content-Type': 'Application/json',
			'Content-Length':bytes.length
		}
	};

  var emitter = this.emitter
	var req = https.request(options, function (res){
    var byteArray = [];
    var size = 0;
    res.on('data', function (data){
      byteArray.push(data);
      size += data.length;
    });
    res.on('end', function (){
      var buf = Buffer.concat(datas, size);
      var content = JSON.parse(buf.toString())
      parse(emitter, content.status, content.receipt)
    });
    res.on('error', function (err) {
      emitter.emit('fault', err)
    });
  }).on('error', function(err){
    emitter.emit('fault', err)
  });
  req.write(bytes);
  req.end();

  return this
}

iOS.prototype.on = function(eventName, callback) {
  this.emitter.on(eventName, callback);
  return this
}

util.inherits(iOS, events.EventEmitter); //继承
module.exports = iOS

