
define(['jquery', 'underscore', 'requtils', 'renderer/baseeditor'], function ($, _, requtils, BaseEditor) {
    'use strict';

    var Utils = requtils.getUtils();

    /* NodeEditor Begin */
    //var NodeEditor = Renderer.NodeEditor = Utils.inherit(Renderer._BaseEditor);
    var NodeEditor = Utils.inherit(BaseEditor);

    _(NodeEditor.prototype).extend({
        template: _.template(
                '<h2><span class="Rk-CloseX">&times;</span><%-renkan.translate("Edit Node")%></span></h2>' +
                '<p><label><%-renkan.translate("Title:")%></label><input class="Rk-Edit-Title" type="text" value="<%-node.title%>"/></p>' +
                '<% if (options.show_node_editor_uri) { %><p><label><%-renkan.translate("URI:")%></label><input class="Rk-Edit-URI" type="text" value="<%-node.uri%>"/><a class="Rk-Edit-Goto" href="<%-node.uri%>" target="_blank"></a></p><% } %>' +
                '<% if (options.show_node_editor_description) { %><p><label><%-renkan.translate("Description:")%></label><textarea class="Rk-Edit-Description"><%-node.description%></textarea></p><% } %>' +
                '<% if (options.show_node_editor_size) { %><p><span class="Rk-Editor-Label"><%-renkan.translate("Size:")%></span><a href="#" class="Rk-Edit-Size-Down">-</a><span class="Rk-Edit-Size-Value"><%-node.size%></span><a href="#" class="Rk-Edit-Size-Up">+</a></p><% } %>' +
                '<% if (options.show_node_editor_color) { %><div class="Rk-Editor-p"><span class="Rk-Editor-Label"><%-renkan.translate("Node color:")%></span><div class="Rk-Edit-ColorPicker-Wrapper"><span class="Rk-Edit-Color" style="background:<%-node.color%>;"><span class="Rk-Edit-ColorTip"></span></span>' +
                '<%= renkan.colorPicker %><span class="Rk-Edit-ColorPicker-Text"><%- renkan.translate("Choose color") %></span></div></div><% } %>' +
                '<% if (options.show_node_editor_image) { %><div class="Rk-Edit-ImgWrap"><div class="Rk-Edit-ImgPreview"><img src="<%-node.image || node.image_placeholder%>" />' +
                '<% if (node.clip_path) { %><svg xmlns="http://www.w3.org/2000/svg" version="1.1" viewbox="0 0 1 1" preserveAspectRatio="none"><path style="stroke-width: .02; stroke:red; fill-opacity:.3; fill:red;" d="<%- node.clip_path %>"/></svg><% }%>' +
                '</div></div><p><label><%-renkan.translate("Image URL:")%></label><input class="Rk-Edit-Image" type="text" value="<%-node.image%>"/></p>' +
                '<p><label><%-renkan.translate("Choose Image File:")%></label><input class="Rk-Edit-Image-File" type="file" accept="image/*"/></p><% } %>' +
                '<% if (options.show_node_editor_creator && node.has_creator) { %><p><span class="Rk-Editor-Label"><%-renkan.translate("Created by:")%></span> <span class="Rk-UserColor" style="background:<%-node.created_by_color%>;"></span><%- shortenText(node.created_by_title, 25) %></p><% } %>' +
                '<% if (options.change_shapes) { %><p><label><%-renkan.translate("Shapes available")%>:</label> <select class="Rk-Edit-Shape">' +
                '<option class="Rk-Edit-Vocabulary-Property" value="circle"<% if (node.shape === "circle") { %> selected<% } %>><%- renkan.translate("Circle") %></option>' +
                '<option class="Rk-Edit-Vocabulary-Property" value="rectangle"<% if (node.shape === "rectangle") { %> selected<% } %>><%- renkan.translate("Square") %></option>' +
                '<option class="Rk-Edit-Vocabulary-Property" value="diamond"<% if (node.shape === "diamond") { %> selected<% } %>><%- renkan.translate("Diamond") %></option>' +
                '<option class="Rk-Edit-Vocabulary-Property" value="polygon"<% if (node.shape === "polygon") { %> selected<% } %>><%- renkan.translate("Hexagone") %></option>' +
                '<option class="Rk-Edit-Vocabulary-Property" value="ellipse"<% if (node.shape === "ellipse") { %> selected<% } %>><%- renkan.translate("Ellipse") %></option>' +
                '<option class="Rk-Edit-Vocabulary-Property" value="star"<% if (node.shape === "star") { %> selected<% } %>><%- renkan.translate("Star") %></option>' +
                '</select></p><% } %>'
        ),
        readOnlyTemplate: _.template(
                '<h2><span class="Rk-CloseX">&times;</span><% if (options.show_node_tooltip_color) { %><span class="Rk-UserColor" style="background:<%-node.color%>;"></span><% } %>' +
                '<span class="Rk-Display-Title"><% if (node.uri) { %><a href="<%-node.uri%>" target="_blank"><% } %><%-node.title%><% if (node.uri) { %></a><% } %></span></h2>' +
                '<% if (node.uri && options.show_node_tooltip_uri) { %><p class="Rk-Display-URI"><a href="<%-node.uri%>" target="_blank"><%-node.short_uri%></a></p><% } %>' +
                '<% if (options.show_node_tooltip_description) { %><p class="Rk-Display-Description"><%-node.description%></p><% } %>' +
                '<% if (node.image && options.show_node_tooltip_image) { %><img class="Rk-Display-ImgPreview" src="<%-node.image%>" /><% } %>' +
                '<% if (node.has_creator && options.show_node_tooltip_creator) { %><p><span class="Rk-Editor-Label"><%-renkan.translate("Created by:")%></span><span class="Rk-UserColor" style="background:<%-node.created_by_color%>;"></span><%- shortenText(node.created_by_title, 25) %></p><% } %>'
        ),
        draw: function() {
            var _model = this.source_representation.model,
            _created_by = _model.get("created_by") || Utils._USER_PLACEHOLDER(this.renkan),
            _template = (this.renderer.isEditable() ? this.template : this.readOnlyTemplate ),
            _image_placeholder = this.options.static_url + "img/image-placeholder.png",
            _size = (_model.get("size") || 0);
            this.editor_$
            .html(_template({
                node: {
                    has_creator: !!_model.get("created_by"),
                    title: _model.get("title"),
                    uri: _model.get("uri"),
                    short_uri:  Utils.shortenText((_model.get("uri") || "").replace(/^(https?:\/\/)?(www\.)?/,'').replace(/\/$/,''),40),
                    description: _model.get("description"),
                    image: _model.get("image") || "",
                    image_placeholder: _image_placeholder,
                    color: _model.get("color") || _created_by.get("color"),
                    clip_path: _model.get("clip_path") || false,
                    created_by_color: _created_by.get("color"),
                    created_by_title: _created_by.get("title"),
                    size: (_size > 0 ? "+" : "") + _size,
                    shape: _model.get("shape") || "circle"
                },
                renkan: this.renkan,
                options: this.options,
                shortenText: Utils.shortenText
            }));
            this.redraw();
            var _this = this,
            closeEditor = function() {
                _this.renderer.removeRepresentation(_this);
                paper.view.draw();
            };

            this.editor_$.find(".Rk-CloseX").click(closeEditor);

            this.editor_$.find(".Rk-Edit-Goto").click(function() {
                if (!_model.get("uri")) {
                    return false;
                }
            });

            if (this.renderer.isEditable()) {

                var onFieldChange = _(function() {
                    _(function() {
                        if (_this.renderer.isEditable()) {
                            var _data = {
                                title: _this.editor_$.find(".Rk-Edit-Title").val()
                            };
                            if (_this.options.show_node_editor_uri) {
                                _data.uri = _this.editor_$.find(".Rk-Edit-URI").val();
                                _this.editor_$.find(".Rk-Edit-Goto").attr("href",_data.uri || "#");
                            }
                            if (_this.options.show_node_editor_image) {
                                _data.image = _this.editor_$.find(".Rk-Edit-Image").val();
                                _this.editor_$.find(".Rk-Edit-ImgPreview").attr("src", _data.image || _image_placeholder);
                            }
                            if (_this.options.show_node_editor_description) {
                                _data.description = _this.editor_$.find(".Rk-Edit-Description").val();
                            }
                            if (_this.options.change_shapes) {
                                if(_model.get("shape")!==_this.editor_$.find(".Rk-Edit-Shape").val()){
                                    _data.shape = _this.editor_$.find(".Rk-Edit-Shape").val();
                                    _data.shape_changed = true;
                                }
                            }
                            _model.set(_data);
                            _this.redraw();
                            // For an unknown reason, we have to set data twice when we change shape, otherwise the image disappears.
                            if(_data.shape_changed===true){
                                _model.set(_data);
                            }
                        } else {
                            closeEditor();
                        }
                    }).defer();
                }).throttle(500);
                
                this.editor_$.on("keyup", function(_e) {
                    if (_e.keyCode === 27) {
                        closeEditor();
                    }
                });

                this.editor_$.find("input, textarea, select").on("change keyup paste", onFieldChange);

                this.editor_$.find(".Rk-Edit-Image-File").change(function() {
                    if (this.files.length) {
                        var f = this.files[0],
                        fr = new FileReader();
                        if (f.type.substr(0,5) !== "image") {
                            alert(_this.renkan.translate("This file is not an image"));
                            return;
                        }
                        if (f.size > (_this.options.uploaded_image_max_kb * 1024)) {
                            alert(_this.renkan.translate("Image size must be under ") + _this.options.uploaded_image_max_kb + _this.renkan.translate("KB"));
                            return;
                        }
                        fr.onload = function(e) {
                            _this.editor_$.find(".Rk-Edit-Image").val(e.target.result);
                            onFieldChange();
                        };
                        fr.readAsDataURL(f);
                    }
                });
                this.editor_$.find(".Rk-Edit-Title")[0].focus();

                var _picker = _this.editor_$.find(".Rk-Edit-ColorPicker");

                this.editor_$.find(".Rk-Edit-ColorPicker-Wrapper").hover(
                        function(_e) {
                            _e.preventDefault();
                            _picker.show();
                        },
                        function(_e) {
                            _e.preventDefault();
                            _picker.hide();
                        }
                );

                _picker.find("li").hover(
                        function(_e) {
                            _e.preventDefault();
                            _this.editor_$.find(".Rk-Edit-Color").css("background", $(this).attr("data-color"));
                        },
                        function(_e) {
                            _e.preventDefault();
                            _this.editor_$.find(".Rk-Edit-Color").css("background", _model.get("color") || (_model.get("created_by") || Utils._USER_PLACEHOLDER(_this.renkan)).get("color"));
                        }
                ).click(function(_e) {
                    _e.preventDefault();
                    if (_this.renderer.isEditable()) {
                        _model.set("color", $(this).attr("data-color"));
                        _picker.hide();
                        paper.view.draw();
                    } else {
                        closeEditor();
                    }
                });

                var shiftSize = function(n) {
                    if (_this.renderer.isEditable()) {
                        var _newsize = n+(_model.get("size") || 0);
                        _this.editor_$.find(".Rk-Edit-Size-Value").text((_newsize > 0 ? "+" : "") + _newsize);
                        _model.set("size", _newsize);
                        paper.view.draw();
                    } else {
                        closeEditor();
                    }
                };

                this.editor_$.find(".Rk-Edit-Size-Down").click(function() {
                    shiftSize(-1);
                    return false;
                });
                this.editor_$.find(".Rk-Edit-Size-Up").click(function() {
                    shiftSize(1);
                    return false;
                });
            } else {
                if (typeof this.source_representation.highlighted === "object") {
                    var titlehtml = this.source_representation.highlighted.replace(_(_model.get("title")).escape(),'<span class="Rk-Highlighted">$1</span>');
                    this.editor_$.find(".Rk-Display-Title" + (_model.get("uri") ? " a" : "")).html(titlehtml);
                    if (this.options.show_node_tooltip_description) {
                        this.editor_$.find(".Rk-Display-Description").html(this.source_representation.highlighted.replace(_(_model.get("description")).escape(),'<span class="Rk-Highlighted">$1</span>'));
                    }
                }
            }
            this.editor_$.find("img").load(function() {
                _this.redraw();
            });
        },
        redraw: function() {
            var _coords = this.source_representation.paper_coords;
            Utils.drawEditBox(this.options, _coords, this.editor_block, this.source_representation.circle_radius * 0.75, this.editor_$);
            this.editor_$.show();
            paper.view.draw();
        }
    });

    /* NodeEditor End */

    return NodeEditor;

});
