/**
 * 这个文件是 用于 在apps/files 页面 的左侧菜单
 * 引入的页面 加载的js 
 * 类似 apps/files_sharing js 里面的app.js
 * 用于监听左侧菜单点击后的事件；
 * 20190924 @kunbei
 */
/*
 * Copyright (c) 2015
 *
 * This file is licensed under the Affero General Public License version 3
 * or later.
 *
 * See the COPYING-README file.
 *
 */
$(function(){
	OCA.Adown = OCA.Adown || {};

	OCA.Adown.Filter = {
		filter: undefined,
		$navigation: $('#app-navigation'),
                $breadcrumb :$("#app-content-download .breadcrumb"),


		_onPopState: function(params) {
			params = _.extend({
				filter: 'download'
			}, params);

			this.setFilter(params.filter);
		},

		setFilter: function (filter) {
			if (filter === this.filter) {
				return;
			}
                        
			this.$navigation.find('a[data-navigation=' + this.filter + ']').parent().removeClass('active');
			OCA.Adown.InfinitScrolling.firstKnownId = 0;
			OCA.Adown.InfinitScrolling.lastGivenId = 0;
                        OCA.Adown.InfinitScrolling.nowtotal = 0;

			this.filter = filter;

			OCA.Adown.InfinitScrolling.$container.animate({ scrollTop: 0 }, 'slow');
			OCA.Adown.InfinitScrolling.$container.children().remove();
			$('#app-content-download  #emptycontent').addClass('hidden');
			$('#no_more_activities').addClass('hidden');
			$('#loading_activities').removeClass('hidden');
			OCA.Adown.InfinitScrolling.ignoreScroll = 0;
                        this.$breadcrumb.find(".crumb:last") .html('<a>'+t('activity','下载完成')+'</a>');

			//this.$navigation.find('a[data-navigation=' + filter + ']').parent().addClass('active');

			OCA.Adown.InfinitScrolling.prefill();
		}
	};

	OCA.Adown.InfinitScrolling = {
		ignoreScroll: 0,
		$container: $('#app-content-download   #container'),
		lastDateGroup: null,
		$content: $(document),
		firstKnownId: 0,
		lastGivenId: 0,
		activities: {},
                nowtotal: 0,

		prefill: function () {
                    
			this.ignoreScroll += 1;
			if (this.$content.scrollTop() + $(window).height() > this.$container.height() - 100) {
                           
				this.ignoreScroll += 1;
				this.loadMoreActivities();
			}
			this.ignoreScroll -= 1;
		},

		onScroll: function () {
                        if (this.ignoreScroll <= 0
                                    && this.$content.scrollTop() + $(window).height() > this.$container.height() - 100) {
                                    this.ignoreScroll = 1;
                                    this.loadMoreActivities();
                            }
                         
		},

		/**
		 * Request a new bunch of activities from the server
		 */
		loadMoreActivities: function () {
			var self = this;
                       // OCA.Adown.Filter.filter = 'files';
                         if( !OCA.Adown.Filter.$navigation.find('a[data-view="download"]').hasClass("active")){
                             return true;
                         }

			$.ajax({
				url: OC.linkToOCS('apps/activity/api/v2/activity', 2) + 'files' + '?format=json&previews=true&since=' + self.lastGivenId +
                                        "&object_type=file_changed&object_id=2",
				type: 'GET',
				beforeSend: function(xhr) {
					xhr.setRequestHeader("Accept-Language", OC.getLocale());
				},
				success: function(response, status, xhr) {
					if (status === 'notmodified') {
						self.handleActivitiesCallback([]);
						self.saveHeaders(xhr.getAllResponseHeaders());
						return;
					}

					self.saveHeaders(xhr.getAllResponseHeaders());
					if (typeof response != 'undefined') {
						self.handleActivitiesCallback(response.ocs.data);
						self.ignoreScroll -= 1;
					}
				}
			});
		},

		/**
		 * Read the X-Activity-First-Known and X-Activity-Last-Given headers
		 * @param headers
		 */
		saveHeaders: function(headers) {
			var self = this;

			headers = headers.split("\n");
			_.each(headers, function (header) {
				var parts = header.split(':');
				if (parts[0].toLowerCase() === 'x-activity-first-known') {
					self.firstKnownId = parseInt(parts[1].trim(), 10);
				} else if (parts[0].toLowerCase() === 'x-activity-last-given') {
					self.lastGivenId = parseInt(parts[1].trim(), 10);
				}
			});
		},

		/**
		 * Append activities to the view or display end/no content
		 * @param data
		 */
		handleActivitiesCallback: function (data) {
			var numActivities = data.length;

			if (numActivities > 0) {
				for (var i = 0; i < data.length; i++) {
					var activity = data[i];
					this.appendActivityToContainer(activity);
				}

				// Continue prefill
				this.prefill();

			} else if (this.$container.children().length === 0) {
				// First page is empty - No activities :(
				var $emptyContent = $('#app-content-download #emptycontent');
				$emptyContent.removeClass('hidden');
				if (OCA.Adown.Filter.filter == 'all') {
					$emptyContent.find('p').text(t('activity', 'This stream will show events like additions, changes & shares'));
				} else {
					$emptyContent.find('p').text(t('activity', 'There are no events for this filter'));
				}
				$('#app-content-download #loading_activities').addClass('hidden');
				this.ignoreScroll = 1;

			} else {
				// Page is empty - No more activities :(
				$('#app-content-download #no_more_activities').removeClass('hidden');
				$('#app-content-download #loading_activities').addClass('hidden');
				this.ignoreScroll = 1;
			}
		},

		appendActivityToContainer: function (activity) {
                      moment.locale("zh-cn");
			activity.timestamp = moment(activity.datetime).valueOf();
			this.makeSureDateGroupExists(activity.timestamp);

			this.activities[activity.activity_id] = activity;
			this.addActivity(activity);
		},

		makeSureDateGroupExists: function(timestamp) {
			var dayOfYear = OC.Util.formatDate(timestamp, 'YYYY-DDD');
			var $lastGroup = this.$container.children().last();

			if ($lastGroup.data('date') !== dayOfYear) {
				var dateOfDay = OC.Util.formatDate(timestamp, 'LL'),
					displayDate = dateOfDay;
                                    moment.locale("zh-cn");
				var today = OC.Util.formatDate(moment(), 'YYYY-DDD');
				if (dayOfYear === today) {
					displayDate = t('activity', 'Today');
				} else {
					var yesterday = OC.Util.formatDate(moment().subtract(1, 'd'), 'YYYY-DDD');

					if (dayOfYear === yesterday) {
						displayDate = t('activity', 'Yesterday');
					}
				}
                              this.displaytime =  escapeHTML(displayDate) ; 

				var content = '<div class="section activity-section group" data-date="' + escapeHTML(dayOfYear) + '">' + "\n"
					+'	<h2>'+"\n"
					+'		<span class="has-tooltip" title="' + escapeHTML(dateOfDay) + '">' + escapeHTML(displayDate) + '</span>' + "\n"
					+'	</h2>' + "\n"
					+'	<div class="boxcontainer">' + "\n"
					+'	</div>' + "\n"
                                        + '<table id="filestable" class="list-container ">'+ "\n"
                                        + '<tbody id="fileList">'+ "\n" 
                                        +  '</tbody></table>'+ "\n" 
					+'</div>';
				var $content = $(content);
				this.processElements($content);
				this.$container.append($content);
				this.lastDateGroup = $content;
                                
			}
		},
                
                addActivity : function(activity){
                    var fileinfo = {} ;
                    var richs = activity.subject_rich[1];
                   if (activity.subject_rich[0].length>0 ) {
                       for(var key in richs){
                           var subject =richs[key];                          
                           fileinfo[subject.id] = richs[key];
                       }                    
                   } else{
                       return false;
                   }
                   var timestamp = this.displaytime;
                  // var content = '<table id="filestable" class="list-container ">'+ "\n"  ;
                       // content += '<tbody id="fileList">'+ "\n"  ;
                       var content = '';
			 
                    if (activity.previews && activity.previews.length) {				
				for (var i = 0; i < activity.previews.length; i++) {
                                    this.nowtotal = this.nowtotal +1;
                                    var preview = activity.previews[i];
                                        var fileid = preview.fileId;
                                        var file = fileinfo[fileid];
                               content += '<tr data-activity-id="' + activity.activity_id + '"> ' + "\n"     
                                    content += '<td class="filename">';
					
					content += ((preview.link) ? '<a class="name"  href="' + file.link + '">' + "\n" : '')
                                                + '<div class="thumbnail-wrapper">'
                                                + '<div class="thumbnail" style="background-image: url(' + preview.source +');"></div>'
                                                + '</div>'
						+ '<span class="nametext extra-data" title="" data-original-title="'+file.name+'">' 
                                                + '<span class="innernametext">'+file.name+'</span> </span>'
						+ ((file.link) ? '</a>' + "\n" : '')
                                                + '</td>';
                                        content += '<td class="date">'
                                                + '<span class="modified"> '+timestamp+' </span></td>';
                                        content += '<td class="date"> <span class="modified">'+t('activity','下载成功')+' </span> </td>';
                                        content += '<td class="column-mtime"> '
                                                +'  <a class="actton" title="" href="' + file.link + '"><span class="ton ton-trfile">  </span> </a>'
                                                + ' <a class="actton" data-original-title="打开文件夹"  href="' + file.link + '"> <span class="ton ton-folder">  </span> </a> '
                                                + ' <a class="actton delete"><span class="ton ton-delete">  </span></a> '
                                                + '</td>';
				}
				 content += '	</tr>' + "\n"  ;
			}
                     //  content += '</tbody></table>'

			var $content = $(content) ;                       
			this.processElements($content);
			this.lastDateGroup.find("#fileList").append($content);
                        
                         /*绑定事件 删除*/
                         $content.find(".actton.delete").bind('click', function(){
                                var $tr = $(this).parents('tr');
                                var activity_id = $tr.data('activity-id');
                                var state  =true; 
                                var $thumbEl = $tr.find('.thumbnail');
				$tr.toggleClass('busy', state);

				if (state) {
					$thumbEl.parent().addClass('icon-loading-small');
				} else {
					$thumbEl.parent().removeClass('icon-loading-small');
				}
                                $.ajax({url: OC.linkToOCS('apps/activity/api/v2/removeitem', 2) + activity_id + '?format=json',
                                      type:'GET', success: function(){
                                                $tr.remove();
                                      }
                                })
                            });
                            
                        OCA.Adown.Filter.$navigation.find('a[data-view="download"]').find("span:last").html('（'+this.nowtotal+'）');
                },

		 

		processElements: function ($element) {
			var self = this;

			$element.find('.avatar').each(function() {
				var element = $(this);
				if (element.data('user-display-name')) {
					element.avatar(element.data('user'), 21, undefined, false, undefined, element.data('user-display-name'));
				} else {
					element.avatar(element.data('user'), 21);
				}
			});

			$element.find('.avatar-name-wrapper').each(function() {
				var element = $(this);
				var avatar = element.find('.avatar');
				var label = element.find('strong');

				$.merge(avatar, label).contactsMenu(element.data('user'), 0, element);
			});

			$element.find('.activity-more-link').click(function() {
				var $moreElement = $(this),
					activityId = $moreElement.closest('.box').data('activity-id'),
					$subject = $moreElement.closest('.activitysubject');

				var activity = self.activities[activityId];
				$subject.html(self.parseMessage(activity.subject_prepared, true));
				self.processElements($subject);
			});

			$element.find('.has-tooltip').tooltip({
				placement: 'bottom'
			});
		}
	};

	//OCA.Adown.Formatter.setAvatarStatus(OCA.Adown.InfinitScrolling.$container.data('avatars-enabled') === 'yes');

/*
	OCA.Adown.Filter.$navigation.find('a[data-navigation]').on('click', function (event) {
		var filter = $(this).attr('data-navigation');
		if (filter !== OCA.Adown.Filter.filter) {
			OC.Util.History.pushState({
				filter: filter
			});
		}
		OCA.Adown.Filter.setFilter(filter);
		event.preventDefault();
	});*/
});
$(document).ready(function() {
    
     $('#app-content-download').on('show', function(e) {
        // OCA.Adown.InfinitScrolling.$container.html("");
         //console.log('00000000000009999----------')
         OCA.Adown.Filter.$navigation = $('#app-navigation');
         OC.Util.History.addOnPopStateHandler(_.bind(OCA.Adown.Filter._onPopState, OCA.Adown.Filter));
         OCA.Adown.Filter.setFilter('download');
	 OCA.Adown.InfinitScrolling.$content.on('scroll', _.bind(OCA.Adown.InfinitScrolling.onScroll, OCA.Adown.InfinitScrolling));
                
		 
	});
})




