/*
 * Copyright (c) 2014 Vincent Petry <pvince81@owncloud.com>
 *
 * This file is licensed under the Affero General Public License version 3
 * or later.
 *
 * See the COPYING-README file.
 *
 */

// HACK: this piece needs to be loaded AFTER the files app (for unit tests)
 $(document).ready(function () {
	(function (OCA) {  
    
		/**
		 * @class OCA.Files.RecentFileList
		 * @augments OCA.Files.RecentFileList
		 *
		 * @classdesc Recent file list.
		 * Displays the list of recently modified files
		 *
		 * @param $el container element with existing markup for the #controls
		 * and a table
		 * @param [options] map of options, see other parameters
		 */
		var RecentFileList = function ($el, options) {
			options.sorting = {
				mode: 'mtime',
				direction: 'desc'
			};
			this.initialize($el, options);
			
		};
		RecentFileList.prototype = _.extend({}, OCA.Files.FileList.prototype,
			/** @lends OCA.Files.RecentFileList.prototype */ {
				id:    OCA.Files.DuoFile.pluginId,
				appName:  OCA.Files.DuoFile.pluginName,

				_clientSideSort: true,
				_allowSelection: true,

				/**
				 * @private
				 */
				initialize: function ($el, options) {
                                   
                                    OCA.Files.FileList.prototype.initialize.apply(this, arguments);
                                    if (this.initialized) {
                                            return;
                                    }
                                     // TODO: consolidate both options
                                    if (options && options._allowSorting) {
                                            this._allowSorting = false;
                                    }
				},

				updateEmptyContent: function () {
					var dir = this.getCurrentDirectory();
					if (dir === '/') {
						// root has special permissions
						this.$el.find('#emptycontent').toggleClass('hidden', !this.isEmpty);
						this.$el.find('#filestable thead th').toggleClass('hidden', this.isEmpty);
					}
					else {
						OCA.Files.FileList.prototype.updateEmptyContent.apply(this, arguments);
					}
				},

				getDirectoryPermissions: function () {
					return OC.PERMISSION_READ | OC.PERMISSION_DELETE;
				},

				/*updateStorageStatistics: function () {
					// no op because it doesn't have
					// storage info like free space / used space
				},*/
                             
				reload: function () {
                                    
					//this.showMask();
					if (this._reloadCall) {
						this._reloadCall.abort();
					}
                                       
					// there is only root
                                        //this._setCurrentDir('/', false);
                                        const  currentLocation  =  FileList.getCurrentDirectory();                        
                                        var albumEtag = '';  

                                        var params = {
                                                location: currentLocation,
                                                mediatypes:  OCA.Files.DuoFile.mediaType(), /*按类型更换*/
                                                features: Gallery.config.getFeatures(),
                                                etag: albumEtag
                                        };

                                        // Only use the folder as a GET parameter and not as part of the URL
                                      this._reloadCall = $.ajax({
						url: Gallery.utility.buildGalleryUrl('files', OCA.Files.DuoFile.Url, params),
						type: 'GET',
						dataType: 'json'
					});
					var callBack = this.reloadCallback.bind(this);
					return this._reloadCall.then(callBack, callBack);
				},

				reloadCallback: function (result) {
                                    
					delete this._reloadCall;
					this.hideMask();
                                       /*
                                        * 处理数据
                                        */
                                       	var albumpath = result.albumpath;
					var updated = result.updated;
					// FIXME albumConfig should be cached as well
					/**@type {{design,information,sorting,error: string}}*/
					var albumConfig = result.albumconfig;
                                        var  currentLocation  = FileList.getCurrentDirectory();
					//Gallery.config.setAlbumPermissions(currentAlbum);
					Gallery.config.setAlbumConfig(albumConfig, albumpath);
					// Both the folder and the etag have to match
                                      
					if ((decodeURIComponent(currentLocation) === albumpath) &&
						(updated === false)) {
						Gallery.imageMap = albumCache.imageMap;
					} else {
                                           
						Gallery._mapFiles(result);
					}
                                        result.files = Gallery.albumMap[albumpath].images;
                                        var subAlbum = Gallery.albumMap[albumpath].subAlbums;
                                        if(subAlbum && subAlbum.length>0){
                                            for(var i in subAlbum){
                                                result.files .push(subAlbum[i]);
                                            }
                                        }
                                    /**
                                     * 这个地方把获取到的数据 格式化成 FileInfo 格式 用于列表展示；
                                     */ 
                                     var files = [];
					if (result.files) {                                             
                                                for(var i in result.files){                                                    
                                                    files.push(new OC.Files.FileInfo( {
                                                        commentsUnread: 0,
                                                        etag: result.files[i].etag,
                                                        hasPreview: false,
                                                        id: result.files[i].fileId,
                                                        isEncrypted: false,
                                                        mimetype: result.files[i].mimetype,
                                                        mountType: "",
                                                        mtime: result.files[i].mTime *1000,
                                                        name: result.files[i].name,
                                                        path: albumpath || "/",
                                                        permissions: result.files[i].permissions,
                                                        sharePermissions: result.files[i].permissions,
                                                        size: result.files[i].size,
                                                        type: result.files[i].type,
                                                    }));
                                                }
                                              
					}
                                        
                                    this.updateStorageStatistics(true);
                                  
                                    // first entry is the root
                                    var currdir =  result.albums[albumpath];
                                    this.dirInfo = new OC.Files.FileInfo( {
                                                        commentsUnread: 0,
                                                        etag: currdir.etag,
                                                        hasPreview: false,
                                                        id: currdir.nodeid,
                                                        isEncrypted: false,                                                      
                                                        mountType: "",
                                                        mtime: currdir.mtime *1000,
                                                        name: currdir.name,
                                                        path: currdir.path,
                                                        permissions: currdir.permissions,
                                                        sharePermissions: currdir.permissions,
                                                        size: currdir.size,
                                                        type: currdir.type,
                                                    });
                                    this.breadcrumb.setDirectoryInfo(this.dirInfo);
                                    /*修改默认breadcrumb 的第一级文字 */
                                    $(".breadcrumb .crumbhome-txt a").html(OCA.Files.DuoFile.pluginName);
                                    if (this.dirInfo.permissions) {
                                            this.setDirectoryPermissions(this.dirInfo.permissions);
                                    } 
                                    this.setFiles( files.sort(this._sortComparator));                                    
                                    return true;                         
				},                        
                                /*OCA。Files。FileList 的方法*/
                               attachFileListUploaderAdd: function(e, upload){
                                 
                               },
                               attachFileListUploaderDone: function(e, upload){
                               
                                    return ;  
                               }
                              
			});

		OCA.Files.RecentFileList = RecentFileList;
              
 	})(OCA);
}); 
            

