var Class = require('../class/Class.js').Class;
var Event = require('../event/Event.js').Event;
var ErrorEvent = require('../event/ErrorEvent.js').ErrorEvent;
var Crypto = require('../common/Crypto.js').Crypto;
var BinaryData     = require("../data/BinaryData.js").BinaryData;
var Response = require("../net/Response.js").Response;
var knox = require('knox');


/**
 * @class S3Client
 */
var S3Client = function(){
    
//    this._client = null;
    
    this.initialize = function(configuration){
        this._client = knox.createClient(configuration);
    };
    
    this.get = function(file, cb){
        var request = this._client.get(file).on('response', function(res){
            var dataLength = 0, buffers = [];
            res.on('data', function(buffer){
                buffers.push(buffer);
                dataLength += buffer.length;
            });
            res.on('end', function(){
                var resultBuffer = new Buffer(dataLength);
                var bufferPosition = 0;
                for(var i = 0, l = buffers.length; i < l; i++){
                    buffers[i].copy(resultBuffer, bufferPosition);
                    bufferPosition += buffers[i].length;
                }
                var response = new Response();
                response.setStatusCode(res.statusCode);
                response.setHeaders(res.headers);
                response.setBody(new BinaryData(resultBuffer, BinaryData.Encoding.BINARY));
                cb(false, response);
            });
        });
        request.on('error',function(err){
            cb(err);
        });
        request.end();
    };
    
    this.set = function(data){
        var that = this;
        var req = this._client.put(Crypto.md5(data), {
            'Content-Length': data.length,
            'Content-Type': 'application/octet-stream'
        });
        req.on('response', function(res){
            if(200 == res.statusCode){
                that.dispatchEvent(new Event(S3Client.Event.LOADED, 'XXX'));
            } else {
                that.dispatchEvent(new ErrorEvent(S3Client.Event.ERROR, {res: res, req:req}, -5, 'S3Client Error'));
            }
        });
        req.end(data);
    };
    
};

S3Client = new Class( new S3Client() );
S3Client.Event = {};
S3Client.Event.LOADED = 'S3Client.Event.LOADED';
S3Client.Event.ERROR = 'S3Client.Event.ERROR';
exports.S3Client = S3Client;
