/**
 * Collection of documents and folders to show in documents list
 */
var DocsCollection = Backbone.Collection.extend({
	model: DocElementModel,
	folder_id: null,
    sort_by: 0,
	all_loaded: false,
	is_next_loading: false,
	expected_rows: 0,
	keywords: '',

	load: function (folder_id, start_row, pagesize, sort_by)
	{
		this.folder_id = (folder_id == null ? 0 : folder_id);
		this.sort_by = (sort_by == null ? 0 : sort_by);
		this.all_loaded = false;
		this.url = '/intranet/rest/documents/folder/' + this.folder_id + '?sort_by=' + this.sort_by;
        this.metadata = 'description,checked_out_to';
		this.expected_rows = pagesize;
		this.is_next_loading = true;

        if (dms_options.cfg_docs_metadata_list_view !== '')
        {
            this.metadata += ',' + dms_options.cfg_docs_metadata_list_view;
        }

		var options = {
			data: {
				show_drafts: 0,
				metadata: this.metadata,
				start: start_row,
				num: pagesize,
				keywords: this.keywords,
				folder_id: this.folder_id
			},
			success: this.onLoaded,
			error: this.onError
		};
		if (start_row > 0)
			options.remove = false;
		this.fetch(options);
	},

	loadAllFolders: function (folder_id)
	{
		this.folder_id = (folder_id == null ? 0 : folder_id);
		this.all_loaded = false;

		this.url = '/intranet/rest/documents/folder/'+this.folder_id+'/folders';

		this.expected_rows = -1;
		this.fetch({success: this.onLoaded, data: {folder_id: folder_id}});
	},


	onLoaded: function (collection, resp, settings)
	{
		if (resp.length < collection.expected_rows || collection.expected_rows < 0)
			collection.all_loaded = true;
		collection.is_next_loading = false;
		if ((typeof(settings.data) !== 'undefined') &&
			(!isNaN(settings.data.folder_id))) {
			store.set('docs_folder_id', settings.data.folder_id);
		}

		collection.trigger('loaded');
	},

	onError: function (collection, resp, settings)
	{
		message = '?message='+settings.xhr.responseText+'&is_error_message=1';

		// Have we lost permissions on the saved folder since last visiting dms? If so just act like the saved folder has been reset to root and don't show the error message.
		if (store.get('docs_folder_id') == settings.data.folder_id)
			message = '';

		// Redirect to root
		window.location = '/intranet/documents'+message+'/#list/0';
	},

	loadNextPortion: function (pageSize, sortBy = 0)
	{
		this.load(this.folder_id, this.length, pageSize, sortBy);
	},

	getDocObject: function (obj_type, obj_id)
	{
		var doc = this.find(function (d) { return (d.get('type') == obj_type && d.getObjId() == obj_id); } );
		if (!doc)
			return null;
		return doc;
	}

});


