/**
 * Created by Serhei on 15.01.15.
 */
define(["marionette", "backbone", "../models/PlaylistItemAdapterModel"],
    function (Marionette, Backbone, PlaylistItemAdapterModel) {
        var PlaylistCollection = Backbone.Collection.extend({
            model: PlaylistItemAdapterModel,

            move: function (pos1, pos2) {
                var list = this.models;
                var i, tmp;
                pos1 = parseInt(pos1, 10);
                pos2 = parseInt(pos2, 10);
                if (pos1 !== pos2 &&
                    0 <= pos1 && pos1 <= list.length &&
                    0 <= pos2 && pos2 <= list.length) {
                    tmp = list[pos1];
                    // move element down and shift other elements up
                    if (pos1 < pos2) {
                        for (i = pos1; i < pos2; i++) {
                            list[i] = list[i + 1];
                            list[i].set('n', i);
                        }
                    }
                    // move element up and shift other elements down
                    else {
                        for (i = pos1; i > pos2; i--) {
                            list[i] = list[i - 1];
                            list[i].set('n', i);
                        }
                    }
                    // put element from position 1 to destination
                    list[pos2] = tmp;
                    list[pos2].set('n', pos2);
                    this.fixOrder();
                    return this;
                }
            },
            insert: function(pos, model){
                if(this.findWhere({id:model.get('id')})){
                    return this;
                }
                model.collection = this;
                var list = this.models;
                var count = list.length;
                for(var i = count; i>pos; i--){
                    list[i] = list[i-1];
                    list[i].set('n', i);
                }
                list[pos] = model;
                list[pos].set('n', pos);
                this.length = list.length;
                this.fixOrder();
                return this;
            },
            remove : function(pos){
                var list = this.models;
                list.splice(pos, 1);
                var count = list.length;
                if(pos == count) return this;

                for(var i = 0;i<count;i++){
                    list[i].set('n', i);
                }
                this.length = list.length;
                this.fixOrder();
                return this;
            },
            fixOrder : function(){
                var list = this.models;
                var count = list.length;
                for(var i = 0; i<count;i++){
                    list[i].attributes.n = this.indexOf(list[i]);
                }
                return this;
            }
        });

        return PlaylistCollection;
    });