/**
* Replacement for the browser Sender class
* uses the batching logic in Javascript Sender.send but sends with node http.request
*/
var Sender = (function () {
    function Sender(config, onSuccess, onError) {
        this._config = config;
        this._onSuccess = onSuccess;
        this._onError = onError;
        this._enableCacheOnError = false;
        this._http = require("http");
        this._url = require("url");
        this._os = require('os');
        this._path = require('path');
        this._fs = require('fs');
    }
    Sender.prototype.send = function (payload) {
        var _this = this;
        var headers = {
            'Content-Type': 'application/json',
            'Content-Length': payload.length
        };
        var endpointUrl = this._config.endpointUrl();
        if (endpointUrl && endpointUrl.indexOf("//") === 0) {
            // use https if the config did not specify a protocol
            endpointUrl = "https:" + endpointUrl;
        }
        var options = {
            host: this._url.parse(endpointUrl).hostname,
            path: this._url.parse(endpointUrl).pathname,
            method: 'POST',
            headers: headers
        };
        var req = this._http.request(options, function (res) {
            res.setEncoding('utf-8');
            //returns empty if the data is accepted
            var responseString = '';
            res.on('data', function (data) {
                responseString += data;
            });
            res.on('end', function () {
                if (typeof _this._onSuccess === "function") {
                    _this._onSuccess(responseString);
                }
                if (_this._enableCacheOnError) {
                    // try to send any cached events if the user is back online
                    if (res.statusCode === 200) {
                        _this._sendFirstFileOnDisk();
                    }
                    else {
                        // cache the payload to send it later
                        _this._storeToDisk(payload);
                    }
                }
            });
        });
        req.on('error', function (error) {
            _this._onErrorHelper(error);
            if (_this._enableCacheOnError) {
                _this._storeToDisk(payload);
            }
        });
        req.write(payload);
        req.end();
    };
    /**
     * enable caching events locally on error
     */
    Sender.prototype.enableCacheOnError = function () {
        this._enableCacheOnError = true;
    };
    /**
    * disable caching events locally on error
    */
    Sender.prototype.disableCacheOnError = function () {
        this._enableCacheOnError = false;
    };
    /**
     * Stores the payload as a json file on disk in the temp direcotry
     */
    Sender.prototype._storeToDisk = function (payload) {
        var _this = this;
        //ensure directory is created
        var direcotry = this._path.join(this._os.tmpDir(), Sender.TEMPDIR);
        if (!this._fs.existsSync(direcotry)) {
            try {
                this._fs.mkdirSync(direcotry);
            }
            catch (error) {
                // failing to create the temp direcotry 
                this._onErrorHelper(error);
                return;
            }
        }
        //create file - file name for now is the timestamp, a better approach would be a UUID but that
        //would require an external dependency 
        var fileName = new Date().getTime() + '.ai.json';
        var fileFullPath = this._path.join(direcotry, fileName);
        // if the file already exist, replace the content
        this._fs.writeFile(fileFullPath, payload, function (error) { return _this._onErrorHelper(error); });
    };
    /**
     * Check for temp telemetry files
     * reads the first file if exist, deletes it and tries to send its load
     */
    Sender.prototype._sendFirstFileOnDisk = function () {
        var _this = this;
        var tempDir = this._path.join(this._os.tmpDir(), Sender.TEMPDIR);
        if (!this._fs.existsSync(tempDir)) {
            return;
        }
        this._fs.readdir(tempDir, function (error, files) {
            if (!error) {
                files = files.filter(function (f) { return _this._path.basename(f).indexOf('.ai.json') > -1; });
                if (files.length > 0) {
                    var firstFile = files[0];
                    var filePath = _this._path.join(tempDir, firstFile);
                    _this._fs.readFile(filePath, function (error, payload) {
                        if (!error) {
                            // delete the file first to prevent double sending
                            _this._fs.unlink(filePath, function (error) {
                                if (!error) {
                                    _this.send(payload);
                                }
                                else {
                                    _this._onErrorHelper(error);
                                }
                            });
                        }
                        else {
                            _this._onErrorHelper(error);
                        }
                    });
                }
            }
            else {
                _this._onErrorHelper(error);
            }
        });
    };
    Sender.prototype._onErrorHelper = function (error) {
        if (typeof this._onError === "function") {
            this._onError(error);
        }
    };
    Sender.TEMPDIR = 'appInsights-node';
    return Sender;
})();
module.exports = Sender;
