/// <reference path="../../node_modules/@types/jquery/index.d.ts"/>

namespace Comments {
    export class Controller {
        public loadUrl;
        public postEndpointUrl;
        private comments: CommentsContainer = new CommentsContainer;
        private form: CommentForm;
        private renderedCount = 0;

        public constructor() {
            let 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);
        }

        public loadComments() {
            $.ajax({
                url: this.loadUrl,
                dataType: 'json'
            }).done((function (data) {
                let $button = $('.comments__show-all');

                for (let i = 0; i < data.length; i++) {
                    if (data.hasOwnProperty(i) && !this.comments.hasId(data[i].id)) {
                        let comment = new Comment(data[i]);
                        this.comments.push(comment);
                        comment.rendered.insertBefore($button);
                    }
                }
                $button.remove();
            }).bind(this));
        }

        public pushComments(data) {
            for (let i = 0; i < data.length; i++) {
                if (data.hasOwnProperty(i)) {
                    let comment = new Comment(data[i]);
                    this.comments.push(comment);
                }
            }
        }

        public addComment(data) {
            let 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'));
        }
    }

    class CommentsContainer {
        [index: number]: Comment;

        push(...args) {
            return Array.prototype.push.apply(this, args);
        }

        hasId(id) {
            let list = Object.keys(this);
            for (let i in list) {
                if (this.hasOwnProperty(i)) {
                    if (this[i].id === id) {
                        return true;
                    }
                }
            }
            return false;
        }
    }

    class CommentForm {
        private owner;
        private form: JQuery;
        private formData;

        constructor(owner: Controller) {
            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 = {};
        }

        private onAddClick(event) {
            event.preventDefault();
            $('.comments__add-error').remove();
            $('.comments__add-popup').show();
            $('.comments__add-back-log').show();
            let target = $(event.target);
            let targetId = 0;
            if (target.hasClass('comments__comment-reply')) {
                targetId = target.parents('.comments__comment').data('comment-id');
            }
            this.formData = {answerTo: targetId};
        }

        private submitFrom(e) {
            e.preventDefault();
            let data = this.form.serializeArray();
            for (let 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 (let 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));
        }
    }

    class Comment {
        private _template: JQuery;
        private _rendered: JQuery;

        private _text;
        private _userName;
        private _date;
        private _level;
        private _id;

        public answerTo = 0;

        constructor(data) {
            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;
        }

        get template() {
            if (this._template !== undefined) return this._template;

            this._template = $('<div class="comments__comment"></div>');
            this._template.append('<div class="comments__comment-text"></div>');
            let 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;
        }

        get rendered() {
            if (this._rendered !== undefined) return this._rendered;
            this._rendered = this.template.clone();
            return this._rendered;
        }

        set text(value) {
            this._text = value;
            this.rendered.find('.comments__comment-text').html(value);
        }

        set userName(value) {
            this._userName = value;
            this.rendered.find('.comments__comment-name').html(value);
        }

        set date(value) {
            this._date = value;
            let 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(' г.', ''));
        }

        set id(value) {
            this._id = value;
            this.rendered.data('comment-id', value);
        }

        get id() {
            return this._id;
        }

        set level(value) {
            this._level = value;
            this.rendered.addClass('comments__comment--level' + value);
        }
    }
}