var http = require('http')
  , ansi = require('./')
  , Canvas = require('canvas')
  , Image = Canvas.Image
  , imageFile = process.argv[2] || __dirname + '/examples/yoshi.png'
  , image = require('fs').readFileSync(imageFile)

var img = new Image()
img.src = image

var server = http.createServer(function (req, res) {
  draw(res);
})

server.listen(8080, function () {
  console.error('HTTP server listening on:', this.address())
})

function draw (stream) {
  var cursor = ansi(stream)
    , pixel = '  '
    , width = img.width
    , scaleW = img.width > width ? width / img.width : 1
    , w = Math.floor(img.width * scaleW)
    , h = Math.floor(img.height * scaleW);

  var canvas = new Canvas(w, h)
    , ctx = canvas.getContext('2d');

  ctx.drawImage(img, 0, 0, w, h);

  var data = ctx.getImageData(0, 0, w, h).data;

  for (var i=0, l=data.length; i<l; i+=4) {
    var r = data[i]
      , g = data[i+1]
      , b = data[i+2]
      , alpha = data[i+3];
    if (alpha > 0) {
      cursor.bg.rgb(r, g, b);
    } else {
      cursor.bg.reset();
    }
    stream.write(pixel);
    if ((i/4|0) % w === (w-1)) {
      cursor.bg.reset();
      stream.write('\n');
    }
  }
  stream.end();
}
