<!--suppress JSAnnotator -->
<template>
	<!-- Page, data-name contains page name which can be used in callbacks -->
	<div class="page " data-name="gallery-photoevents">
		<!-- Top Navbar -->
		<div class="navbar">
			<div class="navbar-inner">
				<div class="title sliding">Photo Events</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-photoevents">
						<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" 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.ASSET_PLAYBACK_MSG02}}</div>
											<div class="item-input-wrap">
												<input type="text" name="StartDateTime" class="StartDateTime"
													placeholder="{{@global.LANGUAGE.ASSET_PLAYBACK_MSG02}}"
													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"  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 photo-list no-hairlines">
							{{#if ShowPhotoList}}
							<div key="VirtualPhotoEventList"
								class="list media-list virtual-list no-hairlines no-margin no-chevron searchbar-found photoList">
							</div>
							{{/if}}
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
</template>


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


			let galleryEvents = Protocol.Helper.getGalleryEvents()

			var ret = {
				filterIsShow: false,
				GalleryEventsTypeList: galleryEvents,
				IsReverse: false,
				IsCheckAll: false,
				alarmPhotoBrowserArr: [],
				VirtualAlarmList: false,
				ShowPhotoList: 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.getPhotoEvents();
							resolve()
						},
						function (err) {
							console.log(err);
							reject()
						}, 'json')
				})
			},

			getPhotoEvents: function (from, to, events) {
				let self = this
				let dId = self.imei ? self.imei.slice(4) : self.$route.query.imei.slice(4)
				let startDate = from ? from : moment().subtract('720', 'hours').format(window.COM_TIMEFORMAT);
				let endDate =  to ? to : moment().format(window.COM_TIMEFORMAT);
				let selectedEvents = events ? events : '4,3,6,2,5,7,8,9,10,11,12,13,14,15,16,17,18'

				self.$app.progressbar.show()

				self.$app.request.get('https://securetrack.co/StandardApiAction_queryPhoto.action?jsession=' + self.JSession + '&devIdno=' + dId + '&filetype=1&alarmType=' + selectedEvents + '&begintime=' + startDate + '&endtime=' + endDate, function (result, xhr, status) {
					self.$app.preloader.hide();
					let p = JSON.parse(result)
					self.$setState({
						ShowPhotoList: true,
					});
					self.$app.progressbar.hide()

					self.initPhotoEventsList(p.infos !== null ? p.infos : [])
				}, function (e) {

				}
				)

			},

			// getGalleryList: function (photoListArr) {
			// 	var self = this;
			// 	self.$app.preloader.show();

			// 	return new Promise((resolve, reject) => {
			// 		self.$app.request.post(API_URL.GET_ALERTPHOTO_LIST, { IMEI: self.imei },
			// 			function (result) {
			// 				if (result.MajorCode == '000') {
			// 					self.$app.methods.setInStorage({ name: 'alarmPhotoList', data: result.Data });

			// 					self.$setState({
			// 						ShowPhotoList: true,
			// 					});
			// 					self.$app.preloader.hide();
			// 				} else {
			// 					self.$app.preloader.hide();
			// 				}
			// 				resolve()
			// 			},
			// 			function (err) {
			// 				console.log(err);
			// 				reject()
			// 			}, 'json')
			// 	})
			// },

			// removePhotos: function (codes) {
			// 	var self = this;
			// 	console.log('before', codes)
			// 	self.$app.preloader.show();
			// 	self.$app.request.promise.post(API_URL.REMOVE_ALERTPHOTO, { "IMEI": self.imei, "codes": codes }, 'json')
			// 		.then(function (result) {
			// 			console.log('after', result)
			// 			if (result.data.MajorCode == '000') {
			// 				self.getGalleryList();
			// 				self.$app.preloader.hide();
			// 			} else {
			// 				self.$app.preloader.hide();
			// 			}
			// 		})
			// 		.catch(function (err) {
			// 			self.$app.preloader.hide();
			// 			console.log(err);
			// 			if (err && err.status === 404) {
			// 				self.dialog.alert(LANGUAGE.PROMPT_MSG002);
			// 			} else {
			// 				self.dialog.alert(LANGUAGE.PROMPT_MSG003);
			// 			}
			// 		});
			// },

			initPhotoEventsList: function (photoListArr) {
				let self = this;
				let listEl = self.$el.find('.photoList');
				self.$app.progressbar.hide()
				let dateArr = self.$app.methods.sortParseDatePhoto(photoListArr, self.$route.query.cam);
				// if (self.IsReverse) { dateArr.reverse(); }
				self.alarmPhotoBrowserArr.length = 0;

				var photoIndex = 0;

				self.PhotoVirtualList = 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: dateArr,
					height: function (item) {
						let height = 0;
						let heightHeader = 40;
						let heightElement = 94;
						let dataLength = 0;
						dataLength = item.data.length;

						if (dataLength % 5) {
							height = heightHeader + heightElement * parseFloat((dataLength + 5 - (dataLength % 5)) / 5);
						} else {
							height = heightHeader + heightElement * parseFloat(dataLength / 5);
						}
						return height;
					},
					emptyTemplate: `<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>';
						ret += '	  <div class="item-content">';
						ret += '		<div class="item-inner">';
						ret += '		  <div class="item-title-row">';
						ret += '			<div class="item-title"> ' + item.title + ' </div>  ';
						ret += '		  </div>          ';
						ret += '		  <div class="item-text">';
						ret += '			<div class="row justify-content-flex-start">';

						for (let d = 0; d < item.data.length; d++) {
							let time = item.data[d].fileTimeStr.split(' ')[1]
							self.alarmPhotoBrowserArr.push('https://securetrack.co/6611/3/5?Type=3&FLENGTH=' + item.data[d].fileSize + '&FOFFSET=' + item.data[d].fileOffset + '&FPATH=' + item.data[d].filePath + '&MTYPE=1&SAVENAME=' + item.data[d].fileTimeStr + '.JPEG&jsession=' + self.JSession);
							ret += '<div class="col-15">';
							ret += '<label class="checkbox check-item photo-check-item display-none">';
							ret += '<input type="checkbox" name="photo-check" file-name="' + item.data[d].Code + '" />';
							ret += '<i class="f7-icons">check</i>';
							ret += '</label>';
							ret += '<a href="#" class="pb-standalone-dark pb-standalone-dark-alarm" data-index="' + photoIndex + '" data-photo="' + item.data[d].Code + '">' +
								'<div class="item-content">' +
								'<div class="item-media photo-item-media">' +
								'<img class="item-path photo-path" data-path="https://securetrack.co/6611/3/5?Type=3&FLENGTH=' + item.data[d].fileSize + '&FOFFSET=' + item.data[d].fileOffset + '&FPATH=' + item.data[d].filePath + '&MTYPE=1&SAVENAME=' + item.data[d].fileTimeStr + '.JPEG&jsession=' + self.JSession + '" src="https://securetrack.co/6611/3/5?Type=3&FLENGTH=' + item.data[d].fileSize + '&FOFFSET=' + item.data[d].fileOffset + '&FPATH=' + item.data[d].filePath + '&MTYPE=1&SAVENAME=' + item.data[d].fileTimeStr + '.JPEG&jsession=' + self.JSession + '">'
							//ret += '<div class="cctv-time"><span class="text-color-white">' + time + '<span></div>' +
							ret +='</div>' +
								'</div>' +
								'</a>';
							ret += '</div> ';
							photoIndex++;
						}

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


						return ret;
					},
				});

				self.alarmPhotoBrowserObj = self.$app.photoBrowser.create({
					theme: 'dark',
					toolbar: false,
					renderNavbar: function () {
						return '<div class="navbar"><div class="navbar-inner"><div class="left"><a href="#" class="link icon-only back"><i class="if-not-ios f7-icons icon-back"></i><i class="if-ios icon icon-back"></i></a></div><div class="title title-color-white">Dashcam Photo</div></div></div>    ';
					},
					photos: self.alarmPhotoBrowserArr
				});
			},
			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, HH:mm';


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



				var pageContent = page.$el.find('.page-content');

				pageContent.on('click', '.pb-standalone-dark-alarm', function (e) {
					self.alarmPhotoBrowserObj.open(+($(this).attr('data-index')));
				});

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


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


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


				form.on('submit', function(e) {
						e.preventDefault();
					 
						let eventsEl = page.$el.find('[name="Events"]');
							
					  let from = moment.utc(startDateTimeEl.val()).format(window.COM_TIMEFORMAT);
					  let to = moment.utc(endDateTimeEl.val()).format(window.COM_TIMEFORMAT);
					 
					  let events = eventsEl.val().toString()

						self.getPhotoEvents(from, to, events)
					 

						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>