/**
 * Created by wushuyi on 2015/8/3.
 */
import Backbone from 'backbone';
import Todos from '../conllections/todo';
import TodoView from './todos';
import global from '../env/global';
import tpl_stats from '../tpl/stats.tpl!txt';

// Todo App View
// --------------
// Our overall **AppView** is the top-level piece of UI.
let AppView = Backbone.View.extend({
    // Instead of generating a new element, bind to the existing skeleton of
    // the app already present in the HTML.
    el: '#todoapp',
    // Our template for the line of statistics at the bottom of the
    statsTemplate: _.template(tpl_stats),
    // Delegated events for creating new items, and clearing completed ones.
    events: {
        'keypress #new-todo': 'createOnEnter',
        'click #clear-completed': 'clearCompleted',
        'click #toggle-all': 'toggleAllComplete'
    },
    // At initialization we bind to the relevant events on the `Todos`
    // collection, when items are added or changed.
    initialize: function () {
        this.allCheckbox = this.$('#toggle-all')[0];
        this.$input = this.$('#new-todo');
        this.$footer = this.$('#footer');
        this.$main = this.$('#main');
        this.listenTo(Todos, 'add', this.addOne);
        this.listenTo(Todos, 'reset', this.addAll);
        this.listenTo(Todos, 'change:completed', this.filterOne);
        this.listenTo(Todos, 'filter', this.filterAll);
        this.listenTo(Todos, 'all', this.render);
        Todos.fetch();
    },
    // Rerendering the app just means refreshing the statistics -- the rest
    // of the app doesn't change.
    render: function () {
        let completed = Todos.completed().length;
        let remaining = Todos.remaining().length;
        if (Todos.length) {
            this.$main.show();
            this.$footer.show();
            this.$footer.html(this.statsTemplate({
                completed: completed,
                remaining: remaining
            }));
            this.$('#filters li a')
                .removeClass('selected')
                .filter('[href="#/' + ( global.TodoFilter || '' ) + '"]')
                .addClass('selected');
        } else {
            this.$main.hide();
            this.$footer.hide();
        }
        this.allCheckbox.checked = !remaining;
    },
    // Add a single todo item to the list by creating a view for it, and
    // appending its element to the `<ul>`.
    addOne: function (todo) {
        let view = new TodoView({model: todo});
        $('#todo-list').append(view.render().el);
    },
    // Add all items in the **Todos** collection at once.
    addAll: function () {
        this.$('#todo-list').html('');
        Todos.each(this.addOne, this);
    },
    filterOne: function (todo) {
        todo.trigger('visible');
    },
    filterAll: function () {
        Todos.each(this.filterOne, this);
    },
    // Generate the attributes for a new todo item.
    newAttributes: function () {
        return {
            title: this.$input.val().trim(),
            order: Todos.nextOrder(),
            completed: false
        };
    },
    // If you hit return in the main input field, create new Todo model,
    // persisting it to localStorage.
    createOnEnter: function (event) {
        if (event.which !== global.ENTER_KEY || !this.$input.val().trim()) {
            return;
        }
        Todos.create(this.newAttributes());
        this.$input.val('');
    },
    // Clear all completed todo items, destroying their models.
    clearCompleted: function () {
        _.invoke(Todos.completed(), 'destroy');
        return false;
    },
    toggleAllComplete: function () {
        let completed = this.allCheckbox.checked;
        Todos.each(function (todo) {
            todo.save({
                'completed': completed
            });
        });
    }
});

export default AppView;