<!--suppress JSAnnotator -->
<template>
	<!-- Page, data-name contains page name which can be used in callbacks -->
	<div class="page " data-name="gallery-videoloops">
		<!-- Top Navbar -->
		<div class="navbar">
			<div class="navbar-inner">
				<div class="title sliding">Video Loops</div>
				<div class="right">
					<a href="#" @click="showFilterDialog" class="link icon-only">
						<i class="f7-icons text-color-white ">filter-1</i>
					</a>
					<a href="#" class="link popup-close" data-popup=".popup-fullscreen-videoloops">
						<i class="f7-icons">close</i>
					</a>
				</div>
			</div>
		</div>

		<div class="page-content ">
			<div class="row  ">
				
				<form name="form" class="block width-100 no-margin-bottom 		{{#js_if "!this.filterIsShow" }}display-none{{/js_if}}">
					<input type="submit" id="submit-form-filter-videoloops" class="display-none" />
					<div class="list no-margin-top no-hairlines no-margin-bottom">
						<ul class="row no-gap">
										  <li class="col-25" key="ReportStartDateTime">
											  <div class="item-content item-input galleryStartDateTimeWrapper" data-input-name="StartDateTime">
												  <div class="item-media text-color-lightgray">
													  <i class="f7-icons icon-calendar"></i>
												  </div>
												  <div class="item-inner">
													  <div class="item-title item-label">{{@global.LANGUAGE.REPORT_PANEL_MSG40}}</div>
													  <div class="item-input-wrap">
														  <input type="text" name="StartDateTime" class="StartDateTime"
															  placeholder="{{@global.LANGUAGE.REPORT_PANEL_MSG40}}"
															  value="{{StartDateTime}}" maxlength="200" readonly>
													  </div>
												  </div>
											  </div>
										  </li>
							<!-- <li class="col-25" key="ReportEndDateTime">
												  <div class="item-content item-input galleryEndDateTimeWrapper" data-input-name="EndDateTime">
													  <div class="item-media text-color-lightgray">
														  <i class="f7-icons icon-calendar"></i>
													  </div>
													  <div class="item-inner">
														  <div class="item-title item-label">{{@global.LANGUAGE.ASSET_PLAYBACK_MSG03}}</div>
														  <div class="item-input-wrap">
															  <input type="text" name="EndDateTime"
																  placeholder="{{@global.LANGUAGE.ASSET_PLAYBACK_MSG03}}" value="{{EndDateTime}}"
																  maxlength="200" readonly>
														  </div>
													  </div>
												  </div>
											  </li> -->
						  
							<!-- <li class="col-25">
								<a class="item-link smart-select smart-select-init custom-smart-select" data-open-in="popup" data-close-on-select="true"  data-searchbar="true">
									<select name="Events" multiple>
										{{#GalleryEventsTypeList}}
										<option value="{{Value}}"   selected>{{Name}}</option>
										{{/GalleryEventsTypeList}}
									</select>
									<div class="item-content item-input">
										<div class="item-media text-color-lightgray">
											<i class="f7-icons icon-report-alarm-report"></i>
										</div>
										<div class="item-inner ">
											<div class="item-title item-label">{{@global.LANGUAGE.ASSET_PLAYBACK_MSG16}}</div>
										</div>
									</div>
								</a>
							</li> -->
											  <li class="col-25 col-25 align-self-center display-flex justify-content-center">
												  <label for="submit-form-filter-videoloops"  class=" col-50 button button-fill color-green elevation-2 ">
													  {{@global.LANGUAGE.COM_MSG00}}
												  </label>
											  </li>
							   
						   
											  
								   
					 
		  
						</ul>
						
					</div>
		  
				</form>
				<div class="col-100 tablet-100">
					<div class="block">
						<div class="list virtual-list video-list no-hairlines">
							{{#if ShowVideoList}}
							<div key="VirtualVideoEventList"
								class="list media-list virtual-list no-hairlines no-margin no-chevron searchbar-found  videoList">
							</div>
							{{/if}}
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
</template>


<script>
	// script must return component object
	return {
		data: function () {
			var self = this;

			var ret = {
				filterIsShow: false,
				IsReverse: false,
				IsCheckAll: false,
				VirtualAlarmList: false,
				ShowVideoList: false,
				JSession: '',
				Asset: POSINFOASSETLIST[self.$route.query.imei] ? POSINFOASSETLIST[self.$route.query.imei] : {}
			};

			return ret;
		},
		methods: {
			getSession: function () {
				var self = this;

				return new Promise((resolve, reject) => {
					self.$app.request.getJSON(API_URL.GET_LIVE_SESSION,
						function (result) {
							let resultJSON = JSON.parse(result)

							self.$setState({
								JSession: resultJSON.jsession
							});
							self.getvideoloops();
							resolve()
						},
						function (err) {
							console.log(err);
							reject()
						}, 'json')
				})
			},

			getvideoloops: function (data) {
				let self = this
				let dId = self.imei ? self.imei.slice(4) : self.$route.query.imei.slice(4)
				// let startDate = self.$route.query.from ? self.$route.query.from : moment().subtract('720', 'hours').format(window.COM_TIMEFORMAT);
				// let endDate = self.$route.query.to ? self.$route.query.to : moment().format(window.COM_TIMEFORMAT);
				//let selectedEvents = self.$route.query.events ? self.$route.query.events : '4,3,6,2,5,7,8,9,10,11,12,13,14,15,16,17,18'
				let year = data?.year ? data.year :  moment().format("YYYY")
				let month = data?.month ? data.month : moment().format("MM")
				let day = data?.day ? data.day : moment().format("DD")
				if(month.length > 1) {
					month =	month.slice(1)
				}
				 
			 

				//console.log(year, month, day)

				self.$app.progressbar.show()


				self.$app.request.get('https://securetrack.co/StandardApiAction_getVideoFileInfo.action?DevIDNO=' + dId + 
				'&CHN='+self.$route.query.cam+'&RECTYPE=0&FILEATTR=2&STORE=0&STREAM=0&RES=0&BEG=0&END=86399&YEAR='+year+'&MON='+month+'&DAY='+day+'&LOC=1&ARM1=0&ARM2=0&jsession=' 
				+ self.JSession, function (result, xhr, status) {
					self.$app.preloader.hide();
					let p = JSON.parse(result)
					self.$setState({
						ShowVideoList: true,
					});
					self.$app.progressbar.hide()
					 if(p.result === 32) {
						self.initvideoloopsList([], true)
					 } else {
						self.initvideoloopsList(p.files ? p.files  : [])
					 }
				}, function (e) {

				}
				)

			},

			initvideoloopsList: function (videoListArr, isDeviceNotOnline) {
				let self = this;
				let listEl = self.$el.find('.videoList');
				self.$app.progressbar.hide()

				


				var videoIndex = 0;

				self.VideoVirtualList = self.$app.virtualList.create({
					el: listEl,
					setListHeight: false,
					// search item by item
					searchAll: function (query, items) {
						let found = [];
						for (let i = 0; i < items.length; i++) {
							if (items[i].title.toLowerCase().indexOf(query.toLowerCase()) >= 0 || query.trim() === '') found.push(i);
						}
						return found;
					},

					//List of array items
					items: videoListArr,
					height: function (item) {
						let height = 0;
						let heightHeader = 40;
						let heightElement = 94;
						let dataLength = 0;
						dataLength = videoListArr.length;

						if (dataLength % 5) {
							height = heightHeader + heightElement * parseFloat((dataLength + 5 - (dataLength % 5)) / 5);
						} else {
							height = heightHeader + heightElement * parseFloat(dataLength / 5);
						}
						return height;
					},
					emptyTemplate: isDeviceNotOnline ? `<li class="item-content"><div class="item-inner"><div class="item-title">${LANGUAGE.COM_MSG144}</div></div></li>` : `<li class="item-content"><div class="item-inner"><div class="item-title">${LANGUAGE.COM_MSG11}</div></div></li>`,

					// Display the each item using Template7 template parameter
					renderItem: function (item, index) {
						//console.log(item);
						let ret = '';

						let list = item.Data;


						//console.log(item)

						ret += '	<li class="col-20">';
						ret += '	  <div class="item-content">';
						ret += '		  <div class="item-text">';
					 
							// self.snapshotBrowserArr.push('https://securetrack.co/6611/3/5?Type=3&FLENGTH=' + item.data[d].fileSize + '&FOFFSET=' + offset + '&FPATH=' + item.data[d].filePath + '&MTYPE=1&SAVENAME=' + item.data[d].fileETime + '.JPEG&jsession=' + self.JSession);
						 
							// ret += '<label class="checkbox check-item video-check-item display-none">';
							// ret += '<input type="checkbox" name="video-check" file-name="' + item.data[d].Code + '" />';
							// ret += '<i class="f7-icons">check</i>';
							// ret += '</label>';
							ret += '<a href="'+item.DownUrl+'" target="_blank" class=" external videoLink" data-index="' + videoIndex + '" >' +
								'<div class="item-content">' +
								'<div class="item-media video-item-media">' +
								'<img class="item-path video-path" src="../resources/images/download.png">'
						 

								'</div>' +
								'</div>' +
								'</a>';
				 
							videoIndex++;
					 

			 
						ret += '		  </div>';
						ret += '		</div>';
			 
						ret += '	</li>';


						return ret;
					},
				});


			},
			showFilterDialog: function () {
				let self = this;
				if(self.filterIsShow) {
					self.$setState({filterIsShow: false}) 
				} else {
					self.$setState({filterIsShow: true}) 
				}
				
			
			},
		},

		on: {
			pageInit: function (e, page) {
				var self = this;


				var datepickerFormat = 'MMMM DD YYYY';


				if (self.$route.query.imei) {
					self.$setState({
						imei: decodeURIComponent(self.$route.query.imei)
					})
				}
				if (self.imei !== undefined) {
					self.getSession();
				}

				let dateTimeEl = page.$el.find('[name="StartDateTime"]');
			 
				let form = page.$el.find('[name="form"]');


				var startPicker = new MaterialDatetimePicker({
					el: dateTimeEl[0],
					format: datepickerFormat,
					openedBy: 'click',
				});
				 


				$$(page.$el).on('click', '.galleryStartDateTimeWrapper', function () {
					startPicker.open();
				});
				 


				form.on('submit', function(e) {
						e.preventDefault();
					 
						//let eventsEl = page.$el.find('[name="Events"]');
						let data = {
							year:  moment.utc(dateTimeEl.val()).format('YYYY'),
							month:  moment.utc(dateTimeEl.val()).format('MM'),
							day:  moment.utc(dateTimeEl.val()).format('DD')
						}	
					 
 					 
					 // let events = eventsEl.val().toString()

						self.getvideoloops(data)
					 

						return false;
				});


				// Pull to refresh content
				var $ptrContent = $$('.ptr-content');
				// Add 'refresh' listener on it
				$ptrContent.on('ptr:refresh', function (e) {
					// Emulate 2s loading
					setTimeout(function () { // Prepend new list element

						self.getGalleryList();
						//$ptrContent.find('ul').prepend(itemHTML);
						// When loading done, we need to reset it
						App.ptr.done(); // or e.detail();
					}, 2000);
				});
			},
		}
	};
</script>