/// <reference path="PhantomOutput.js"/>
/// <reference path="PhantomPngRenderer.js"/>

global.PhantomPngGenerator = function PhantomPngGenerator(console, stdin, pageFactory) {
    this._console = console;
    this._stdin = stdin;
    this._pageFactory = pageFactory;
}

PhantomPngGenerator.prototype = {
    waitForInputThenGenerate: function () {
        var input = this._stdin.readLine();
        if (input.length > 0) {
            var printInformation = JSON.parse(input);
            if(printInformation.dataFile){ // used when Debug manually.
                var fs = require('fs');
                input = fs.read(printInformation.dataFile)
                printInformation = JSON.parse(input);
            }
            var self = this;
            this._page = this._createPage(printInformation);
            this._page.onError = function (error, trace) {
                self.onError(error, trace);
            };
            this._renderer = new PhantomPngRenderer(printInformation.outputPath);
            this._output = new PhantomOutput(printInformation.coherenceId);
            this._generate(printInformation.html);
        }
    },

    onError: function (text, trace) {
        this._output.errors.push({ message: text, trace: trace });
    },

    _generate: function (html) {
        var self = this;
        this._page.onCallback = function () {
            self._onPhantomCallback();
        };

        this._page.setContent(html, "http://localhost");
    },

    _createPage: function (printInformation) {
        var page = this._pageFactory();
        page.viewportSize = { width: printInformation.width, height: printInformation.height };
        return page;
    },

    _onPhantomCallback: function () {
        var renderResult = this._renderer.render(this._page);
        this._output.setResult(renderResult);
        this._outputAndWaitForNewInput();
    },

    _outputAndWaitForNewInput: function () {
        this._console.log(JSON.stringify(this._output));
        this.waitForInputThenGenerate();
    }

};