### codetube
    Copyright (C) 2011 payload payload@lavabit.com
    Copyright (C) 2011 dodo dodo.the.last@gmail.com

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>
###

{ CommitView } = require './commit'
{ Backbone } = require '../Backbone'

class CommitsView extends Backbone.View

    initialize: ({@el}) ->
        @views = {}
        @model.bind 'add', @add_commit
        @one 'hide:progressbar', @hide_progressbar
        do @render
        super

    hide_progressbar: =>
        @$(".spinner").css 'visibility', 'hidden'
        @$(".progressbar").css 'visibility', 'hidden'
        @one 'show:progressbar', @show_progressbar

    show_progressbar: =>
        @$(".spinner").css 'visibility', 'visible'
        @$(".progressbar").css 'visibility', 'visible'
        @one 'hide:progressbar', @hide_progressbar


    render: () =>
        for cid, view of @views
            view.render()
        @$('.more-commits').click (ev) =>
            @trigger 'more-commits'
            @show_progressbar()
            return false
        this

    add_commit: (commit) =>
        view = new CommitView model:commit
        @views[commit.cid] = view
        do view.render

        i = @model.indexOf(commit)
        if i is 0
            if @model.models.length is 1
                @$('.tail').before view.el
            else
                @$("#"+@views[@model.at(1).cid].cid).after view.el
        else
            @$("#"+@views[@model.at(i-1).cid].cid).before view.el


        @$('.headline .counter').text @model.length



module.exports = { CommitsView }
