<!--suppress JSAnnotator -->
<template>
	<!-- Page, data-name contains page name which can be used in callbacks -->
	<div class="page " data-name="gallery-videoevents">
		<!-- Top Navbar -->
		<div class="navbar">
			<div class="navbar-inner">
				<div class="title sliding">{{#if isLoopVideo}} Loop Video {{else}}Video Events{{/if}}</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-videoevents">
						<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 ">
					<input type="submit" id="submit-form-filter-videoevents" 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>
							{{#unless isLoopVideo}}
							<li class="col-50">
								<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>
						{{/unless}}
					 
							<li class="col-25   align-self-center display-flex justify-content-end">
								<label for="submit-form-filter-videoevents" class=" col-50 button button-fill color-green elevation-2 ">
									{{@global.LANGUAGE.COM_MSG00}}
								</label>
							</li>
						</ul>
					</div>
				</form>
				<div class="col-50" style="height: 400px;    padding-top: 56px;">
					<iframe src="{{playbackSrc}}" id="playbackVideo" width="100%" title="Live" allow="fullscreen"
						allowfullscreen="" class="iframe-fullscreen"></iframe>
				</div>
				<div class="col-50 tablet-50">

					<table id="table-video-events" class="mdl-data-table " style="width:100%">
						<thead>
							<tr>

								<th>#</th>
								<th>Play</th>
								<th>Time</th>
								<th>Channel</th>
								<th>Size</th>

							</tr>
						</thead>
						<tbody>
							{{#VideoData}}
							<tr>
								<td>{{Number}}</td>
								<td>
									<div class="item-media text-color-lightgray no-padding link playVideo"><i
											class="f7-icons icon-cctv-play"></i></div>
								</td>
								<td>{{Time}}</td>
								<td>{{Chn}}</td>
								<td>{{Size}}</td>
							</tr>
							{{/VideoData}}
						</tbody>
					</table>
				</div>
			</div>
		</div>
	</div>
</template>


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


			let videoEvents = Protocol.Helper.getVideoEvents()



			var ret = {
				isLoopVideo : self.$route.query.isLoopVideo == 'true' ? true : false,
				GalleryEventsTypeList: videoEvents,
				DATATABLEVideoEvents: false,
				IsReverse: false,
				IsCheckAll: false,
				VirtualAlarmList: false,
				ShowVideoList: false,
				JSession: '',
				Asset: POSINFOASSETLIST[self.$route.query.imei] ? POSINFOASSETLIST[self.$route.query.imei] : {},
				swfobject: null,
				playbackSrc: API_URL.PLAYBACK_PLAYER_SRC //+ "?" + self.$app.utils.serializeObject(playbackSrcParams),


			};

			return ret;
		},
		methods: {


			// Initialize video plugin
			initPlayer: function () {
				let self = this
				var playingStatusArray = [];

				for (var i = 0; i < 101; i++) {
					playingStatusArray.push(false);
				}
				var _isVodMode = 0 //video = 0, playback = 1;
				isInitFinished = false;
				var width = 600;
				var hieght = 400
				var strLang = 'en'
				var options = {
					domId: "cmsv6flash",
					isVodMode: _isVodMode == "1" ? true : false,
					width: width,
					height: hieght,
					lang: strLang == "" ? "en" : strLang
				}

				self.$setState({
					swfobject: new Cmsv6Player(options)
				})
				self.initFlash();
			},

			// Execute after plugin initialization is complete
			initFlash: function () {
				let self = this
				//console.log('self.swfobject', self.swfobject)
				if (typeof self.swfobject == "undefined" ||
					typeof self.swfobject.setWindowNum == "undefined") {
					setTimeout(initFlash, 50);
				} else {
					// Initialize plugin language
					var language = 'en.xml'  //getValue('languagePath');
					if (!language) {
						return;
					}
					self.swfobject.setLanguage(language);
					// First create all windows
					self.swfobject.setWindowNum(36);
					// Reconfigure the current number of windows
					var windowNum = 1
					self.swfobject.setWindowNum(windowNum);
					// Set server information
					var serverIp = '47.241.210.146'
					var serverPort = '6605'
					self.swfobject.setServerInfo(serverIp, serverPort);
					//isInitFinished = true;
				}
			},
			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.getVideoEvents();
							resolve()
						},
						function (err) {
							console.log(err);
							reject()
						}, 'json')
				})
			},

			getVideoEvents: function (data) {
				let self = this
				let dId = self.imei ? self.imei.slice(4) : self.$route.query.imei.slice(4)
				//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)
				// }
				function objectToQueryString(obj) {
					const keyValuePairs = [];
					for (const key in obj) {
						if (obj.hasOwnProperty(key)) {
							keyValuePairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(obj[key]));
						}
					}
					return keyValuePairs.join('&');
				}


				self.$app.progressbar.show()
			 

				let dataObject = {
					DevIDNO: dId,
					LOC: 1,
					CHN: self.$route.query.cam,
					YEAR: year,
					MON: month,
					DAY: day,
					RECTYPE: self.isLoopVideo ? 0 : 1,
					FILEATTR: 2,
					BEG: 0,
					END: 86399,
					ARM1: data?.arm1Value ? data?.arm1Value : 0,
					ARM2: data?.arm2Value ? data?.arm2Value : 0,
					RES: 0,
					STREAM: -1,
					STORE: 0,
					jsession: self.JSession
				}
 

				let payload = objectToQueryString(dataObject);


				self.$app.request.get('https://securetrack.co/StandardApiAction_getVideoFileInfo.action', payload, function (result, xhr, status) {
					self.$app.preloader.hide();
					let videoData = JSON.parse(result)

					//console.log('videoData', videoData)
				if(videoData.files) {
						
					for (var i = 0; i < videoData.files.length; i++) {
						let params = new URLSearchParams(new URL(videoData.files[i].PlaybackUrl).search);
						let playbackData = {
								DevIDNO: dId,
								jsession: self.JSession,
								DownType: params.get('DownType'),
								FILELOC:  params.get('FILELOC'),
								FILESVR:  params.get('FILESVR'),
								FILECHN:  params.get('FILECHN'),
								FILEBEG:  params.get('FILEBEG'),
								FILEEND:  params.get('FILEEND'),
								PLAYIFRM: params.get('PLAYIFRM'),
								PLAYFILE: params.get('PLAYFILE'),
								PLAYBEG:  params.get('PLAYBEG'),
								PLAYEND:  params.get('PLAYEND'),
								PLAYCHN:  params.get('PLAYCHN'),
								YEAR:     params.get('YEAR'),
								MON:      params.get('MON'),
								DAY:      params.get('DAY')
						};

						let downTaskUrl = videoData.files[i].DownTaskUrl

						let fbtmMatch = downTaskUrl.match(/fbtm=([^&]*)/);
						let fetmMatch = downTaskUrl.match(/fetm=([^&]*)/);

						let fbtm = fbtmMatch ? fbtmMatch[1] : null;
						let fetm = fetmMatch ? fetmMatch[1] : null;


						let bytes = videoData.files[i].len;
						let megabytes = bytes / 1048576;

						videoData.files[i].Number = i + 1
						videoData.files[i].Time = fbtm + ' - ' + fetm;
						videoData.files[i].Chn = videoData.files[i].chn == '0' ? '1' : '2'
						videoData.files[i].Size = megabytes.toFixed(2) + " MB";
						videoData.files[i].PlaybackData = playbackData
					}
				//	console.log(videoData.files);
				}
					

	 
					self.updateTableData(videoData.files ? videoData.files : [])


					self.$setState({
						ShowVideoList: true,
						//VideoData: videoData.files
					});
					self.$app.progressbar.hide()



				}, function (e) {

				}
				)

			},


			stopPlayback: function () {
				let self = this;
				self.swfobject.getObjectById("cmsv6flash").stopVideo(0);
			},


			updateTableData: function (data) {
					let table = $('#table-video-events').DataTable();
					table.clear(); 
 

				

					for (let item of data) {
						let playbackDataString = JSON.stringify(item.PlaybackData);
						let playButtonHTML = `<div class="item-media text-color-lightgray no-padding link playVideo" data-playback='${playbackDataString}'><i class="f7-icons icon-cctv-play"></i></div>`;

							table.row.add([
									item.Number,	
									playButtonHTML,				
									item.Time,
									item.Chn,
									item.Size
							]);
					}
					table.draw(); 
			}
				
		},

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

				//self.initPlayer()
				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 arm1Value = 0;
					let arm2Value = 0;

					let eventsEl = page.$el.find('[name="Events"]');
   				let selectedValues = eventsEl.val();

					if (selectedValues && selectedValues.length) {
							selectedValues.forEach(selectedValue => {
									const valueParts = selectedValue.split('_'); 
									const actualValue = parseInt(valueParts[valueParts.length - 1]); 

									if (valueParts[0] === "2") { 
											arm2Value += Math.pow(2, actualValue - 1);
									} else { 
											arm1Value += Math.pow(2, actualValue - 1);
									}
							});
					}

					// console.log('arm1:', arm1Value);
					// console.log('arm2:', arm2Value);

					//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'),
						arm1Value,
						arm2Value
					}
					// let events = eventsEl.val().toString()

					self.getVideoEvents(data)


					return false;
				});





				self.DATATABLEVideoEvents = $('#table-video-events').DataTable({
					searching: false,
					buttons: {
						dom: {
							container: {
							//	className: 'datatable-additional-buttons '
							}
						},
						buttons: []
					},
					order: [[1, 'asc']],
					columnDefs: [{ targets: [ 1, 3 ], orderable: false,  }],
					lengthMenu: [10, 25, 50, 100],
					pageLength: 10,

				});
 


				$('#table-video-events tbody').on('click', 'div.playVideo', function(e) {
						let playbackDataString = $(this).attr('data-playback');
						let playbackData = JSON.parse(playbackDataString);

						var iframe = document.getElementById('playbackVideo');
						var iframeWindow = iframe.contentWindow;
						iframeWindow.postMessage({ type: 'startPlayback', data: playbackData }, 'https://securetrack.co');

				});




				// 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>