/**
 * Create a image from text.
 * @function lib.image.text2image
 * @param {string} text - Source text.
 * @param {string} filename - Image file name.
 * @param {object} options - Optional settings.
 * @param {number} options.width - Image width.
 * @param {number} options.height - Image height.
 * @param {string} options.color - Text color.
 * @param {string} [options.backgroundColor] - Image background color.
 * @param {string} [options.fontFamily] - Text font family.
 * @param {string} [options.fontFile] - Custom font file.
 * @param {number} [options.cornerRadius] - Corner radius size.
 * @param {function} callback - Callback when done.
 * @author Taka Okunishi
 *
 */
var path = require('path'),
    fs = require('fs'),
    object = require('../../lib/object'),
    deepCopy = object.deepCopy;

exports = module.exports = function (text, filename, options, callback) {
    try {
        require.resolve('fabric');
    } catch (e) {
        var msg = 'npm module "fabric" not found. Please try: \n\n\t$ npm install fabric \n\n If you got some error, ' +
            'Try node-canvas install guild listed here \n \thttps://github.com/LearnBoost/node-canvas/wiki/_pages \n';
        callback(new Error(msg));
        return;
    }
    var fabric = require('fabric').fabric;
    var settings = deepCopy(options, {
        width: 100,
        height: 200,
        fontSize: 24,
        color: '#DDD',
        backgroundColor: '#FFF',
        fontFamily: 'Hoefler Text',
        cornerRadius: 0,
        borderWidth: 0
    });


    var width = settings.width,
        height = settings.height;


    var canvas = fabric.createCanvasForNode(width, height);


    if (options.fontFile) {
        var fontFile = path.resolve(options.fontFile),
            fontName = path.basename(fontFile, path.extname(fontFile));

        if (canvas.Font) {
            try {
                var font = new canvas.Font(fontName, fontFile);
                canvas.contextContainer.addFont(font);
                settings.fontFamily = fontName;
            } catch (e) {
                console.error('Failed to load file:', fontFile);
                console.error(e.stack);
            }
        } else {
            console.warn('Custom font not supported!');
        }
    }


    var borderWidth = settings.borderWidth;
    canvas.add(
        new fabric.Rect({
            width: settings.width - borderWidth * 2,
            height: settings.height - borderWidth * 2,
            rx: settings.cornerRadius,
            ry: settings.cornerRadius,
            fill: settings.backgroundColor,
            originX: 'center',
            originY: 'center',
            left: width / 2,
            top: height / 2,
            borderColor: '#3AF',
            hasBorders: true,
            stroke: settings.borderColor,
            strokeWidth: borderWidth
        })
    );
    canvas.add(
        new fabric.Text(text, {
            fontFamily: settings.fontFamily,
            fontSize: settings.fontSize,
            fill: settings.color,
            originX: 'center',
            originY: 'center',
            left: width / 2,
            top: height / 2,
            lineHeight: 1
        })
    );
    var inStream = canvas.createPNGStream(),
        outStream = fs.createWriteStream(filename);

    inStream.on('data', function (chunk) {
        outStream.write(chunk);
    });
    inStream.on('error', function (err) {
        callback && callback(err);
        callback = null;
    });
    inStream.on('end', function () {
        callback && callback();
    });
};

