import PathNode from './path-node';
import NODE_MAP from './node-map';
import renderAllAttr from './utils/render-all-attributes';
import { htmlEncode } from '../common';

var ImageNode = (function (PathNode) {
    function ImageNode () {
        PathNode.apply(this, arguments);
    }

    if ( PathNode ) ImageNode.__proto__ = PathNode;
    ImageNode.prototype = Object.create( PathNode && PathNode.prototype );
    ImageNode.prototype.constructor = ImageNode;

    ImageNode.prototype.geometryChange = function geometryChange () {
        this.allAttr(this.mapPosition());
        this.invalidate();
    };

    ImageNode.prototype.optionsChange = function optionsChange (e) {
        if (e.field === "src") {
            this.allAttr(this.mapSource());
        }

        PathNode.prototype.optionsChange.call(this, e);
    };

    ImageNode.prototype.mapPosition = function mapPosition () {
        var rect = this.srcElement.rect();
        var tl = rect.topLeft();

        return [
            [ "x", tl.x ],
            [ "y", tl.y ],
            [ "width", rect.width() + "px" ],
            [ "height", rect.height() + "px" ]
        ];
    };

    ImageNode.prototype.renderPosition = function renderPosition () {
        return renderAllAttr(this.mapPosition());
    };

    ImageNode.prototype.mapSource = function mapSource (encode) {
        var src = this.srcElement.src();

        if (encode) {
            src = htmlEncode(src);
        }

        return [ [ "xlink:href", src ] ];
    };

    ImageNode.prototype.renderSource = function renderSource () {
        return renderAllAttr(this.mapSource(true));
    };

    ImageNode.prototype.template = function template () {
        return "<image preserveAspectRatio='none' " + (this.renderId()) + " " + (this.renderStyle()) + " " + (this.renderTransform()) + " " + (this.renderOpacity()) +
               (this.renderPosition()) + " " + (this.renderSource()) + " " + (this.renderDefinitions()) + ">" +
               "</image>";
    };

    return ImageNode;
}(PathNode));

NODE_MAP.Image = ImageNode;

export default ImageNode;