<!--suppress JSAnnotator -->
<template>
<div class="page" data-name="cctv">
  <div class="navbar">
    <div class="navbar-inner sliding">
      <div class="left">
        <!--<a href="#" class="link back">
          <i class="icon icon-back"></i>
          <span class="ios-only">Back</span>
        </a>-->
      </div>
      <div class="title">
        {{@global.LANGUAGE.HOME_MSG047 }}
      </div>
      <div class="right">
        <a href="#" class="link popup-close" data-popup=".popup-fullscreen-cctv">
          <i class="f7-icons">close</i>
        </a>
      </div>
    </div>
  </div>
  <div class="page-content">
    <div class="content-wrapper with-sidebar {{#if isPanelOpened}}sidebar-opened{{/if}}">
      <div class="content-sidebar left">
        <div @click="togglePanel" class="panel-control ">
          <i class="f7-icons size-16">chevron_right</i>
        </div>
        <div class="list links-list no-margin">
          <ul>
            <li><a @click="togglePanel" href="#" >{{ @global.LANGUAGE.COM_MSG135 }}</a></li>
          </ul>
        </div>
        {{#if isNoAssets}}
        <div key="no-assets-key" class="block">
          <div class="block-inner">{{@global.LANGUAGE.PROMPT_MSG0137}}</div>
        </div>
        {{/if}}
        <div class="list media-list virtual-list no-hairlines no-hairlines-between no-margin no-chevron  searchbar-found group-list-with-assets assetListVideo" >

        </div>
      </div>

      <div class="content">
        <div class="content-top-control bg-color-white elevation-6">
          <div class="segmented segmented-custom segmented-custom-cctv">
            <button @click="sendCCTVCommand('playAll')"
                    class="button tooltip-init {{#js_if 'this.activeCommand === \'playAll\''}}button-active{{/js_if}}"
                    data-tooltip="{{@global.LANGUAGE.CCTV_MSG001}}"
            >
              <i class="f7-icons icon icon-cctv-play"></i>
            </button>
            <button @click="sendCCTVCommand('stopAll')"
                    class="button tooltip-init {{#js_if 'this.activeCommand === \'stopAll\''}}button-active{{/js_if}}"
                    data-tooltip="{{@global.LANGUAGE.CCTV_MSG002}}"
            >
              <i class="f7-icons icon icon-cctv-stop"></i>
            </button>
            <button @click="sendCCTVCommand('history')"
                    class="button tooltip-init"
                    data-tooltip="History"
            >
              <i class="f7-icons icon icon-calendar"></i>
            </button>
            <button @click="sendCCTVCommand('oneScreen')"
                    class="button tooltip-init {{#js_if 'this.activeCommand === \'oneScreen\''}}button-active{{/js_if}}"
                    data-tooltip="{{@global.LANGUAGE.CCTV_MSG003}}"
            >
              <i class="f7-icons icon icon-rectangle"></i>
            </button>
            <button @click="sendCCTVCommand('fourScreens')"
                    class="button tooltip-init {{#js_if 'this.activeCommand === \'fourScreens\''}}button-active{{/js_if}}"
                    data-tooltip="{{@global.LANGUAGE.CCTV_MSG004}}"
            >
              <i class="f7-icons icon icon-cctv-4"></i>
            </button>
            <button @click="sendCCTVCommand('nineScreens')"
                    class="button tooltip-init {{#js_if 'this.activeCommand === \'nineScreens\''}}button-active{{/js_if}}"
                    data-tooltip="{{@global.LANGUAGE.CCTV_MSG005}}"
            >
              <i class="f7-icons icon icon-cctv-9"></i>
            </button>
            <button @click="sendCCTVCommand('allScreens')"
                    class="button tooltip-init {{#js_if 'this.activeCommand === \'allScreens\''}}button-active{{/js_if}}"
                    data-tooltip="{{@global.LANGUAGE.CCTV_MSG006}}"
            >
              <i class="f7-icons icon icon-cctv-12"></i>
            </button>
            <button @click="sendCCTVCommand('fullScreen')"
                    class="button tooltip-init"
                    data-tooltip="{{@global.LANGUAGE.CCTV_MSG007}}"
            >
              <i class="f7-icons icon icon-cctv-full"></i>
            </button>
          </div>
        </div>
        <iframe src="{{cctvSrc}}" id="videScreens" width="100%" title="Live" allow="fullscreen" allowfullscreen="" class="iframe-fullscreen" style=""></iframe>
      </div>
    </div>
  </div>
</div>
</template>

<script>
  // script must return component object
  return {
    name: 'cctv',
    data: function () {
      let self = this;

      let cctvSrcParams = {
        lang: "en"
      }
      return {
        isNoAssets: false,
        isPanelOpened: true,
        activeCommand: 'playAll',
        cctvSrc: API_URL.CCTV_SRC + "?" + self.$app.utils.serializeObject(cctvSrcParams),
        cctvScreen: null
      }
    },
    methods: {
      sendCCTVCommand: function (command){
        if(!command){
          return
        }

        switch (command) {
          case 'playAll':
            this.cctvScreen.contentWindow.postMessage("playAllVideo()", this.cctvSrc);
            break;
          case 'stopAll':
            this.cctvScreen.contentWindow.postMessage("pauseAllVideo()", this.cctvSrc);
            break;
          case 'oneScreen':
            this.cctvScreen.contentWindow.postMessage("channelMultiple(1)", this.cctvSrc);
            break;
          case 'fourScreens':
            this.cctvScreen.contentWindow.postMessage("channelMultiple(4)", this.cctvSrc);
            break;
          case 'nineScreens':
            this.cctvScreen.contentWindow.postMessage("channelMultiple(9)", this.cctvSrc);
            break;
          case 'allScreens':
            this.cctvScreen.contentWindow.postMessage("channelMultiple(16)", this.cctvSrc);
            break;
          case 'fullScreen':
            this.launchFullScreen(this.cctvScreen)
            break;
          case 'history':
            this.chooseCameraDialog()
            break;
        }
        if(command !== 'fullScreen'){
          this.$setState({
            activeCommand: command
          })
        }
      },
	  
	  chooseCameraDialog: function () {
				let self = this;
		 
				let dialogBody = `
                      <p class="">
                       
                      </p>
                      <div class="list no-hairlines no-margin">
                          <ul>
							<li>
								<label class="item-radio item-content">
									<input type="radio" name="cam-radio" value="cam1" />
									<i class="icon icon-radio"></i>
									<div class="item-inner">
                                      <div class="item-title">Cam 1</div>
                                 	</div>
								</label>
							</li>
								<li>
								<label class="item-radio item-content">
									<input type="radio" name="cam-radio" value="cam2" />
									<i class="icon icon-radio"></i>
									<div class="item-inner">
                                      <div class="item-title">Cam 2</div>
                                 	</div>
								</label>
							</li>
                          </ul>
                      </div>
                  `;
				  var buttons = [
						{
							text: LANGUAGE.COM_MSG16,
							cssClass: Template7.global.DEALER_TEXT_COLOR_CLASS ? Template7.global.DEALER_TEXT_COLOR_CLASS : 'color-red',
							onClick: function (dialog) {
								self.closeAllPopups();
								let selectedRadio =  dialog.$el.find('[name="cam-radio"]:checked').val()
								
								if(selectedRadio == 'cam1') {
									self.showHistoryDialog();
								} else if (selectedRadio == 'cam2') {
									self.showHistoryDialog();
								}
							}
						},
					];
					if (self.$app.width < 400) {
						buttons.push({ text: LANGUAGE.COM_MSG01, cssClass: 'color-black' })
					} else {
						buttons.unshift({ text: LANGUAGE.COM_MSG01, cssClass: 'color-black' });
					}

					self.$app.dialog.create({
						title: 'Choose Dashcam',
						text: dialogBody,
						//cssClass: 'dialog-bigger',
						verticalButtons: self.$app.width < 400,
					  buttons: buttons,
					}).open();

	  },
	  showHistoryDialog: function () {
				let self = this;
		 
				let dialogBody = `
                      <p class="">
                       
                      </p>
                      <div class="list no-hairlines no-margin">
                          <ul>
							<li>
								<label class="item-radio item-content">
									<input type="radio" name="history-radio" value="snapshots" />
									<i class="icon icon-radio"></i>
									<div class="item-inner">
                                      <div class="item-title">Snapshots</div>
                                 	</div>
								</label>
							</li>
								<li>
								<label class="item-radio item-content">
									<input type="radio" name="history-radio" value="videoloops" />
									<i class="icon icon-radio"></i>
									<div class="item-inner">
                                      <div class="item-title">Loop Video</div>
                                 	</div>
								</label>
							</li>
						  	<li>
								<label class="item-radio item-content">
									<input type="radio" name="history-radio" value="photoevents" />
									<i class="icon icon-radio"></i>
									<div class="item-inner">
                                      <div class="item-title">Photo Events</div>
                                 	</div>
								</label>
							</li>   
								<li>
								<label class="item-radio item-content">
									<input type="radio" name="history-radio" value="videoevents" />
									<i class="icon icon-radio"></i>
									<div class="item-inner">
                                      <div class="item-title">Video Events</div>
                                 	</div>
								</label>
							</li>
                          </ul>
                      </div>
                  `;
				  var buttons = [
						{
							text: LANGUAGE.COM_MSG16,
							cssClass: Template7.global.DEALER_TEXT_COLOR_CLASS ? Template7.global.DEALER_TEXT_COLOR_CLASS : 'color-red',
							onClick: function (dialog) {
								self.closeAllPopups();
								let selectedRadio =  dialog.$el.find('[name="history-radio"]:checked').val()
								
								if(selectedRadio == 'snapshots') {
									self.$app.methods.showSnapShotsPopup()
								} else if(selectedRadio == 'photoevents') {
									self.$app.methods.showPhotoEventsPopup()
								} else if(selectedRadio == 'videoevents') {
									self.$app.methods.showVideoEventsPopup()
								} else if (selectedRadio == 'videoloops') {
									self.$app.methods.showVideoLoopsPopup()
								}
							}
						},
					];
					if (self.$app.width < 400) {
						buttons.push({ text: LANGUAGE.COM_MSG01, cssClass: 'color-black' })
					} else {
						buttons.unshift({ text: LANGUAGE.COM_MSG01, cssClass: 'color-black' });
					}

					self.$app.dialog.create({
						title: 'Select History',
						text: dialogBody,
						//cssClass: 'dialog-bigger',
						verticalButtons: self.$app.width < 400,
					  buttons: buttons,
					}).open();

	  },
	  closeAllPopups: function () {
				var self = this;

				var popup = self.$app.popup.get('.popup-admin-panel2');
				if (popup) {
					popup.close();
				}
				popup = self.$app.popup.get('.popup-report-panel');
				if (popup) {
					popup.close();
				}

	  },
      openLiveStream: function (deviceNo, chnIndex){
        this.cctvScreen.contentWindow.postMessage("playVideo("+deviceNo+", "+chnIndex+")", this.cctvSrc);
      },
      launchFullScreen: function(element) {
        if(element.requestFullscreen) {
          element.requestFullscreen();
        } else if(element.mozRequestFullScreen) {
          element.mozRequestFullScreen();
        } else if(element.webkitRequestFullscreen) {
          element.webkitRequestFullscreen();
        } else if(element.msRequestFullscreen) {
          element.msRequestFullscreen();
        }
      },

      /*exitFullscreen: function () {
        if(document.exitFullscreen) {
          document.exitFullscreen();
        } else if(document.mozExitFullScreen) {
          document.mozExitFullScreen();
        } else if(document.webkitExitFullscreen) {
          document.webkitExitFullscreen();
        }
      },*/
      togglePanel: function (){
        this.$setState({
          isPanelOpened: !this.isPanelOpened
        })
      },
      getAssetsWithCamera: function (groups){
        const map = new Map();
        let filteredGroups = [];
        for (var i = 0; i < groups.length; i++) {
          if (groups[i].Assets && groups[i].Assets.length){
            for (var y = 0; y < groups[i].Assets.length; y++) {
              if((groups[i].Assets[y].PRDTFeatures & Protocol.ProductFeatures.Camera) > 0){
                if(!map.has(groups[i].Code)){
                  map.set(groups[i].Code, true);
                  filteredGroups.push({
                    Name: groups[i].Name,
                    Code: groups[i].Code,
                    Assets: [groups[i].Assets[y]]
                  })
                }else{
                  //let group = newList.find( el => el.Code === groups[i].Code );
                  //group.Assets.push(item.IMEI);
                  //filteredGroups.push(groups[i].Assets[y])
                }
                console.log('yes', groups[i].Assets[y].Name)
              }
            }
          }
        }
        return filteredGroups
      }
    },
    on: {
      pageInit: function (e, page) {
        var self = this;
        self.cctvScreen = document.getElementById("videScreens");
        var groupListEl = page.$el.find('.assetListVideo');

        var groups = self.$app.methods.getFromStorage("groupList");
        var contactList = self.$app.methods.getFromStorage('contactList');

        var filteredGroups = self.getAssetsWithCamera(groups)

        if(!filteredGroups || !filteredGroups.length){
          self.$setState({
            isNoAssets: true
          })
        }

        self.VirtualList = self.$app.virtualList.create({
          el: groupListEl,
          // setListHeight: false,
          // search item by item
          searchAll: function (query, items) {
            self.$app.accordion.open('.accordion-item');
            var found = [];
            query = query.trim().toLowerCase();
            for (var i = 0; i < items.length; i++) {
              if (items[i].Assets && items[i].Assets.length || query === '') {
                for (var y = 0; y < items[i].Assets.length; y++) {
                  if (items[i].Assets[y].Name.toLowerCase().indexOf(query) >= 0 ||
                    items[i].Assets[y].IMEI.toLowerCase().indexOf(query) >= 0 ||
                    items[i].Assets[y].IMSI.toLowerCase().indexOf(query) >= 0 ||
                    items[i].Assets[y].StockNumber.toLowerCase().indexOf(query) >= 0 ) {
                    if (!found.includes(i)) {
                      found.push(i);
                    }
                    virtualList.items[i].Assets[y].hidden = false;
                  }else{
                    virtualList.items[i].Assets[y].hidden = true;
                  }
                }
              }
            }

            var prevItems = virtualList.items;
            self.VirtualList.replaceAllItems(prevItems);
            return found; //return array with mathced indexes
          },
          //List of array items
          items: filteredGroups && filteredGroups.length ? filteredGroups : [],
          height: function (item) {
            var height = 65.37;
            if (item && item.Assets && item.Assets.length ) {
              for (var i = item.Assets.length - 1; i >= 0; i--) {
                var asset = POSINFOASSETLIST[item.Assets[i].IMEI];
                if (asset) {
                  var assetFeaturesStatus = Protocol.Helper.getAssetStateInfo(asset);
                  if(assetFeaturesStatus.stats === false){
                    height += 68;
                  } else if (assetFeaturesStatus && assetFeaturesStatus.voltage && assetFeaturesStatus.fuel || assetFeaturesStatus && assetFeaturesStatus.battery && assetFeaturesStatus.fuel || assetFeaturesStatus && assetFeaturesStatus.battery && assetFeaturesStatus.voltage) {
                    height += 121.75;
                  }else{
                    height += 100.38;
                    if(asset.DriverCode) height += 21.37;
                  }
                } else{
                  height += 68;
                }
              }
            }
            return height;
          },
          // Display the each item using Template7 template parameter
          renderItem: function (item, index) {
            var ret = '';
            // var groupImg = self.$app.methods.getGroupImg(item);

            if (item) {
              ret +=  `<li class="item-content" data-code="${ item.Code }" data-name="${ item.Name }" data-index="${ index }" >
                        <div class="item-inner accordion-item accordion-item-opened">
                          <div class="group-line group-line-header item-link ">`;
              if (item.Assets && item.Assets.length){
                if (item.Assets.length>1){
                  ret +=     `<div class="item-title weight-500">${ item.Name }<span class="weight-300">(${ item.Assets.length } ${ LANGUAGE.ASSET_GROUPS_MSG09 })</span></div>`;
                }else{
                  ret +=      `<div class="item-title weight-500">${ item.Name }<span class="weight-300">(${ item.Assets.length } ${ LANGUAGE.ASSET_GROUPS_MSG14 })</span></div>`;
                }
              }else{
                ret +=        `<div class="item-title weight-500">${ item.Name }<span class="weight-300">(${ LANGUAGE.ASSET_GROUPS_MSG15 })</span></div>`;
              }
              ret +=        `</div>
                            <div class="accordion-item-content ">`;

              if (item.Assets && item.Assets.length) {
                $.each(item.Assets,function(key, val){
                  var asset = POSINFOASSETLIST[val.IMEI];
                  var assetFeaturesStatus = Protocol.Helper.getAssetStateInfo(asset);
                  var assetImg = self.$app.methods.getAssetImg(val, {'assetList':true});
                  var solutiontype = val.SolutionType ? val.SolutionType : LANGUAGE.PROMPT_MSG068;
                  var solutiontypeIcon = Protocol.Helper.getSolutionTypeIcon(solutiontype);
                  var assetType = asset && asset.AssetType ? asset.AssetType.toLowerCase() : '';
                  var driver = null;
                  if(asset && asset.DriverCode){
                    let index = contactList.findIndex((item) =>  item.Code === asset.DriverCode)
                    driver = index !== -1 ? contactList[index] : null
                  }
                  //console.log(assetFeaturesStatus);
                  if (!val.hidden) {
                    if (asset && assetFeaturesStatus && assetFeaturesStatus.stats) {
                      ret += `
                          <div class="group-line item-content groupLineAsset " data-imei="${ val.IMEI }" data-id="${ val.Id }" data-name="${ val.Name }" data-imsi="${ val.IMSI }" title="${ val.Name }">
                            <div class="item-media">
                              ${ assetImg }
                              <i class="icon-status-fix ${ assetFeaturesStatus.status.state }" data-id="status-state${ val.IMEI }" title="${ assetFeaturesStatus.status.value }"></i>
                            </div>
                            <div class="item-inner">
                              <div class="item-title-row ">
                                <div class="item-title">
                                  <i data-id="signal-state${ val.IMEI }" class="f7-icons size-16 icon-signal ${ assetFeaturesStatus.GSM.state }" ></i>
                                  <i data-id="satellite-state${ val.IMEI }" class="f7-icons size-16 icon-satellite ${ assetFeaturesStatus.GPS.state }"></i>
                                  <i data-id="solutiontype-${ val.IMEI }" class="f7-icons size-16 ${ solutiontypeIcon } text-color-lightblue" title="${ solutiontype }"></i>`;
                                  if(assetType === 'boat' || assetType === 'jetski'){
                                  ret += `<i data-id="power-state-${val.IMEI}" class="f7-icons size-16 icon-power ${assetFeaturesStatus.boatStates.shorePower.state}" title="${LANGUAGE.COM_MSG124} ${assetFeaturesStatus.boatStates.shorePower.value}"></i>
                                          <i data-id="pump-state-${val.IMEI}" class="f7-icons size-16 icon-pump ${assetFeaturesStatus.boatStates.bilgePump.state}" title="${LANGUAGE.COM_MSG125} ${assetFeaturesStatus.boatStates.shorePower.value}"></i>`;
                                  }

                      ret += `  </div>
                              </div>
                              <div class="item-subtitle weight-500" title="${ val.Name }">${ val.Name }</div>
                              <div class="divider"></div>
                              <div class="item-text">
                                <div class="row no-gutter">`;
                                if (assetFeaturesStatus.speed) {
                      ret +=              `<div class="col-50">
                                              <i class="f7-icons size-16 icon-speed asset_list_icon text-color-lightgray vertical-middle"></i>
                                              <span data-id="speed-value${ val.IMEI }" class="size-12 vertical-middle">${ assetFeaturesStatus.speed.value }</span>
                                          </div>`;
                                      }
                                      if (assetFeaturesStatus.voltage) {
                      ret +=              `<div class="col-50">
                                              <i class="f7-icons size-16 icon-voltage asset_list_icon text-color-lightgray vertical-middle"></i>
                                              <span data-id="voltage-value${ val.IMEI }" class="size-12 vertical-middle">${ assetFeaturesStatus.voltage.value }</span>
                                          </div>`;
                                      }
                                      if (assetFeaturesStatus.battery) {
                      ret +=              `<div class="col-50">
                                              <i class="f7-icons size-16 icon-battery asset_list_icon text-color-lightgray vertical-middle"></i>
                                              <span data-id="battery-value${ val.IMEI }" class="size-12 vertical-middle">${ assetFeaturesStatus.battery.value }</span>
                                          </div>`;
                                      }
                                      if (assetFeaturesStatus.temperature) {
                      ret +=              `<div class="col-50">
                                              <i class="f7-icons size-16 icon-temperature asset_list_icon text-color-lightgray vertical-middle"></i>
                                              <span data-id="temperature-value${ val.IMEI }" class="size-12 vertical-middle">${ assetFeaturesStatus.temperature.value }</span>
                                          </div>`;
                                      }
                                      if (assetFeaturesStatus.fuel) {
                      ret +=              `<div class="col-50">
                                              <i class="f7-icons size-16 icon-fuel asset_list_icon text-color-lightgray vertical-middle"></i>
                                              <span data-id="fuel-value${ val.IMEI }" class="size-12 vertical-middle">${ assetFeaturesStatus.fuel.value }</span>
                                          </div>`;
                                      }
                                      if (driver) {
                      ret+=               `<div class="col-50" title="${driver.FirstName} ${driver.SubName}">
                                              <i class="f7-icons size-16 icon-driver asset_list_icon text-color-lightgray vertical-middle"></i><span data-id="driver-value${val.IMEI}" class="size-12 vertical-middle" >${driver.FirstName ? driver.FirstName : driver.SubName}</span>
                                           </div>`;
                                      }
                      ret+=   `</div>`;
                      ret+=   `<div class="row no-gutter">
                                  <div class="col-50 cursor-pointer open-stream-player" data-chanel="1" data-imei="${ val.IMEI }" data-name="${ val.Name }">
                                    <i class="f7-icons size-16 icon-cctv-cam asset_list_icon text-color-red vertical-middle"></i>
                                    <span data-id="cam1-value${ val.IMEI }" class="size-12 vertical-middle">${ LANGUAGE.CCTV_MSG000 }1</span>
                                  </div>
                                  <div class="col-50 cursor-pointer open-stream-player" data-chanel="2" data-imei="${ val.IMEI }" data-name="${ val.Name }">
                                    <i class="f7-icons size-16 icon-cctv-cam asset_list_icon text-color-red vertical-middle"></i>
                                    <span data-id="cam2-value${ val.IMEI }" class="size-12 vertical-middle">${ LANGUAGE.CCTV_MSG000 }2</span>
                                  </div>
                              </div>
                            </div>
                          </div>`;
                    }
                  }
                });
              }

              ret +=  `</div>
                     </div>
                    </li>`;
            }

            return ret;
          },
        });

        page.$el.on('click', '.open-stream-player', function (e){
          console.log($$(this).data('chanel'))
          let imei = "0" + $$(this).data('imei');
          let chanel = $$(this).data('chanel')
          self.openLiveStream(imei, chanel)
        })
      },
      pageBeforeRemove: function(){
        this.VirtualList.destroy()
      }
    }
  }
</script>