/// <reference path="../../node_modules/@types/jquery/index.d.ts"/>
var Comments;
(function (Comments) {
    var Controller = (function () {
        function Controller() {
            this.comments = new CommentsContainer;
            this.renderedCount = 0;
            var showAll = $('.comments__show-all');
            this.renderedCount = showAll.parent().find('.comments__comment').length;
            this.loadUrl = showAll.data('load-url');
            showAll.on('click', this.loadComments.bind(this));
            $('.comments__add-popup-close').click(function (e) {
                e.preventDefault();
                $('.comments__add-popup').hide();
                $('.comments__add-back-log').hide();
            });
            this.form = new CommentForm(this);
        }
        Controller.prototype.loadComments = function () {
            $.ajax({
                url: this.loadUrl,
                dataType: 'json'
            }).done((function (data) {
                var $button = $('.comments__show-all');
                for (var i = 0; i < data.length; i++) {
                    if (data.hasOwnProperty(i) && !this.comments.hasId(data[i].id)) {
                        var comment = new Comment(data[i]);
                        this.comments.push(comment);
                        comment.rendered.insertBefore($button);
                    }
                }
                $button.remove();
            }).bind(this));
        };
        Controller.prototype.pushComments = function (data) {
            for (var i = 0; i < data.length; i++) {
                if (data.hasOwnProperty(i)) {
                    var comment = new Comment(data[i]);
                    this.comments.push(comment);
                }
            }
        };
        Controller.prototype.addComment = function (data) {
            var comment = new Comment(data);
            this.comments.push(comment);
            if (data.answeredTo)
                comment.rendered.insertAfter($('.comments').find('[data-comment-id=' + data.answerTo + ']'));
            else
                comment.rendered.insertBefore($('.comments__show-all'));
        };
        return Controller;
    }());
    Comments.Controller = Controller;
    var CommentsContainer = (function () {
        function CommentsContainer() {
        }
        CommentsContainer.prototype.push = function () {
            var args = [];
            for (var _i = 0; _i < arguments.length; _i++) {
                args[_i] = arguments[_i];
            }
            return Array.prototype.push.apply(this, args);
        };
        CommentsContainer.prototype.hasId = function (id) {
            var list = Object.keys(this);
            for (var i in list) {
                if (this.hasOwnProperty(i)) {
                    if (this[i].id === id) {
                        return true;
                    }
                }
            }
            return false;
        };
        return CommentsContainer;
    }());
    var CommentForm = (function () {
        function CommentForm(owner) {
            this.owner = owner;
            $('.comments__add-link').on('click', this.onAddClick.bind(this));
            $('.comments').on('click', '.comments__comment-reply', this.onAddClick.bind(this));
            this.form = $('.comments__add-popup-form');
            this.form.on('submit', this.submitFrom.bind(this));
            this.owner.postEndpointUrl = this.form.attr('action');
            this.formData = {};
        }
        CommentForm.prototype.onAddClick = function (event) {
            event.preventDefault();
            $('.comments__add-error').remove();
            $('.comments__add-popup').show();
            $('.comments__add-back-log').show();
            var target = $(event.target);
            var targetId = 0;
            if (target.hasClass('comments__comment-reply')) {
                targetId = target.parents('.comments__comment').data('comment-id');
            }
            this.formData = { answerTo: targetId };
        };
        CommentForm.prototype.submitFrom = function (e) {
            e.preventDefault();
            var data = this.form.serializeArray();
            for (var i in data) {
                if (data.hasOwnProperty(i)) {
                    this.formData[data[i].name] = data[i].value;
                }
            }
            $('.comments__add-error').remove();
            console.dir({ UserComments: this.formData });
            $.ajax({
                url: this.owner.postEndpointUrl,
                data: { UserComments: this.formData },
                dataType: 'json',
                type: 'post'
            }).done((function (data) {
                console.dir(data);
                if (data.errors) {
                    for (var fieldName in data.errors) {
                        if (data.errors.hasOwnProperty(fieldName))
                            $('<span class="comments__add-error">' + data.errors[fieldName][0] + '</span>').insertAfter(this.form.find('[name=' + fieldName + ']'));
                    }
                }
                else {
                    //this.form.parent().find('.comments__add-popup-close').click();
                    this.form.html('<p>Ваш комментарий успешно отправлен. После одобрения модератором он появится на сайте.</p>');
                    setTimeout((function () {
                        this.form.parent().find('.comments__add-popup-close').click();
                    }).bind(this), 3000);
                    //this.owner.addComment(data.result);
                }
            }).bind(this)).fail((function (xhr) {
                console.dir(xhr.responseText);
            }).bind(this)).always((function () {
                this.formData = [];
            }).bind(this));
        };
        return CommentForm;
    }());
    var Comment = (function () {
        function Comment(data) {
            this.answerTo = 0;
            this.id = data.id;
            this.userName = data.userName;
            this.date = data.datetime;
            this.text = data.text;
            this.level = data.answerTo == 0 ? 1 : 2;
            this.answerTo = data.answerTo;
        }
        Object.defineProperty(Comment.prototype, "template", {
            get: function () {
                if (this._template !== undefined)
                    return this._template;
                this._template = $('<div class="comments__comment"></div>');
                this._template.append('<div class="comments__comment-text"></div>');
                var info = $('<div class="comments__comment-info"></div>');
                info.append('<div class="comments__comment-name"></div>');
                info.append('<div class="comments__comment-date"></div>');
                info.append('<div class="comments__comment-reply">Ответить</div>');
                this._template.append(info);
                return this._template;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Comment.prototype, "rendered", {
            get: function () {
                if (this._rendered !== undefined)
                    return this._rendered;
                this._rendered = this.template.clone();
                return this._rendered;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Comment.prototype, "text", {
            set: function (value) {
                this._text = value;
                this.rendered.find('.comments__comment-text').html(value);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Comment.prototype, "userName", {
            set: function (value) {
                this._userName = value;
                this.rendered.find('.comments__comment-name').html(value);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Comment.prototype, "date", {
            set: function (value) {
                this._date = value;
                var dateObject = new Date(value);
                this.rendered.find('.comments__comment-date').html(dateObject.toLocaleString("ru", {
                    year: 'numeric',
                    month: 'long',
                    day: 'numeric',
                    hour: '2-digit',
                    minute: '2-digit'
                }).replace(' г.', ''));
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Comment.prototype, "id", {
            get: function () {
                return this._id;
            },
            set: function (value) {
                this._id = value;
                this.rendered.data('comment-id', value);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Comment.prototype, "level", {
            set: function (value) {
                this._level = value;
                this.rendered.addClass('comments__comment--level' + value);
            },
            enumerable: true,
            configurable: true
        });
        return Comment;
    }());
})(Comments || (Comments = {}));
