<!--suppress JSAnnotator -->
<template>
<!-- Page, data-name contains page name which can be used in callbacks -->
    <div class="page " data-name="share-assets"> <!-- page-with-subnavbar -->
    <!-- Top Navbar -->
        <div class="navbar">
            <div class="navbar-inner">
                <a href="#" class="link back">
                    <i class="icon icon-back"></i>
                </a>
                <div class="title sliding">{{@global.LANGUAGE.SHARE_ASSETS_MSG000}}</div>
                <div class="right">
                    {{#js_if 'this.CurrentTab === "my-assets"'}}
                    <a href="/shared-assets/create/" class="link icon-only ">
                        <i class="f7-icons icon-header-added"></i>
                    </a>
                    {{else}}
                    <a href="#" @click="openSubscribeCodeDialog" class="link icon-only" >
                        <i class="f7-icons icon-header-added"></i>
                    </a>
                    {{/js_if}}
                    <!--<label for="{{CurrentFormButtonSubmit}}" class="link icon-only">
                        <i class="f7-icons icon-header-apply"></i>
                    </label>-->
                </div>
            </div>
        </div>

        <div class="toolbar tabbar tabbar-custom toolbar-top">
            <div class="toolbar-inner">
                <a href="#my-assets" class="tab-link tab-link-active">
                    {{@global.LANGUAGE.SHARE_ASSETS_MSG001}}
                </a>
                <a href="#subscribed" class="tab-link">
                    {{@global.LANGUAGE.SHARE_ASSETS_MSG002}}
                </a>
            </div>
        </div>

        <div class="bottom-section-wrapper bottom-section-button-wrapper bg-color-white">
            <div class="row">
                {{#js_if 'this.CurrentTab === "my-assets"'}}
                <a href="/shared-assets/create/" data-view=".view-left" class="col link button button-fill color-green elevation-2">
                    <i class="f7-icons icon-header-added"></i>
                    {{@global.LANGUAGE.SHARE_ASSETS_MSG028}}
                </a>
                {{else}}
                <a href="#" @click="openSubscribeCodeDialog" class="col link button button-fill color-green elevation-2" >
                    <i class="f7-icons icon-header-added"></i>
                    {{@global.LANGUAGE.COM_MSG37}}
                </a>
                {{/js_if}}
            </div>
        </div>
        <!--<div class="searchbar-backdrop"></div>-->
        <div class="tabs-animated-wrap">
            <div class="tabs">
                <div class="page-content tab tab-active" id="my-assets">

                    <form class="searchbar searchbar-shared-assets-my overflow-hidden" >
                        <div class="searchbar-inner">
                            <div class="searchbar-input-wrap">
                                <input type="search" placeholder="{{@global.LANGUAGE.COM_MSG02}}" title="{{@global.LANGUAGE.COM_MSG02}}">
                                <i class="searchbar-icon"></i>
                                <span class="input-clear-button"></span>
                            </div>
                            <span class="searchbar-disable-button text-color-gray">{{@global.LANGUAGE.COM_MSG01}}</span>
                        </div>
                    </form>

                    <div key="hide-on-search-block-my-assets" class="block searchbar-hide-on-search text-align-center {{#unless isMyAssetsLoaded}}display-none{{/unless}}">{{@global.LANGUAGE.SHARE_ASSETS_MSG003}}</div>

                    <div class="block searchbar-not-found">
                        <div class="block-inner">{{@global.LANGUAGE.PROMPT_MSG008}}</div>
                    </div>

                    {{#unless isMyAssetsLoaded}}
                    <div key="skeleton-virtual-list-my-assets" class="list media-list no-hairlines no-chevron no-margin-top">
                        <ul>
                            {{#each '123'}}
                            <li>
                                <a href="#" class="item-link item-content asset skeleton-text skeleton-effect-blink" >
                                    <div class="item-inner">
                                        <div class="item-title-row align-items-center">
                                            <div class="item-title">
                                                Asset Name
                                            </div>
                                            <div class="item-after">
                                                ic
                                            </div>
                                        </div>
                                        <div class="item-text">
                                            geofence address goes here, it can be very long, two lines.. some time it take 3 or even 4 lines
                                        </div>
                                    </div>
                                </a>
                            </li>
                            {{/each}}
                        </ul>
                    </div>
                    {{/unless}}

                    <div class="list media-list virtual-list no-chevron no-margin-top no-hairline-bottom searchbar-found myAssetsList" >
                        <!-- keep it empty -->
                    </div>
                </div>

                <div class="page-content tab" id="subscribed">
                    <form class="searchbar searchbar-shared-assets-subscribed overflow-hidden" >
                        <div class="searchbar-inner">
                            <div class="searchbar-input-wrap">
                                <input type="search" placeholder="{{@global.LANGUAGE.COM_MSG02}}" title="{{@global.LANGUAGE.COM_MSG02}}">
                                <i class="searchbar-icon"></i>
                                <span class="input-clear-button"></span>
                            </div>
                            <span class="searchbar-disable-button text-color-gray">{{@global.LANGUAGE.COM_MSG01}}</span>
                        </div>
                    </form>

                    <div class="block searchbar-hide-on-search text-align-center {{#unless isSubscribedLoaded}}display-none{{/unless}}">{{@global.LANGUAGE.SHARE_ASSETS_MSG004}}</div>

                    <div class="block searchbar-not-found">
                        <div class="block-inner">{{@global.LANGUAGE.PROMPT_MSG008}}</div>
                    </div>
                    {{#unless isSubscribedLoaded}}
                    <div key="skeleton-virtual-list-subscribed-assets" class="list media-list no-hairlines no-chevron no-margin-top">
                        <ul>
                            {{#each '123'}}
                            <li>
                                <a href="#" class="item-link item-content asset skeleton-text skeleton-effect-blink" >
                                    <div class="item-inner">
                                        <div class="item-title-row align-items-center">
                                            <div class="item-title">
                                                Asset Name
                                            </div>
                                            <div class="item-after">
                                                ic
                                            </div>
                                        </div>
                                        <div class="item-text">
                                            geofence address goes here, it can be very long, two lines.. some time it take 3 or even 4 lines
                                        </div>
                                    </div>
                                </a>
                            </li>
                            {{/each}}
                        </ul>
                    </div>
                    {{/unless}}

                    <div class="list media-list virtual-list no-chevron no-margin-top no-hairline-bottom searchbar-found subscribedAssetsList" >
                        <!-- keep it empty -->
                    </div>
                </div>


            </div>
        </div>

    </div>



</template>


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

            var ret = {
                CurrentTab: 'my-assets',
                isMyAssetsLoaded: false,
                isSubscribedLoaded: false,

                VirtualListMyAssets: null,
                VirtualListSubscribed: null,
                SearchbarMyAssets: null,
                SearchbarSubscribed: null,
            };

           /* ret = self.$app.methods.getFromStorage('userInfo');
            ret.TimeZoneList = Protocol.Helper.getTimezoneList(ret.TimeZoneID || ret.TimeZone);
            ret.CurrentFormButtonSubmit = 'submit-form-user';*/

            return ret;
        },

        methods: {
            initListMyAssetsList: function (assetList) {
                let self = this;

                let listEl = self.$el.find('.myAssetsList');

                self.VirtualListMyAssets = self.$app.virtualList.create({
                    el: listEl,
                    items: assetList || [],
                    //cache: false,
                    searchAll: function (query, items) {
                        let found = [];
                        for (let i = 0; i < items.length; i++) {
                            if (items[i].Name.toLowerCase().indexOf(query.toLowerCase()) >= 0 ||
                              items[i].IMEI.toLowerCase().indexOf(query.toLowerCase()) >= 0 ||
                              query.trim() === ''
                            ){
                                found.push(i);
                            }
                        }
                        return found; //return array with mathced indexes
                    },
                    height: function (item) {
                        return self.$app.theme === 'ios' ? 75.75 : 81.3
                    },
                    renderItem: function (item, index) {
                        let ret = `
                            <li data-index="${index}">`;

                        ret += `  <a href="#" class="link color-custom ripple-color-red item-menu-button bigger-touch-area myAssetsMenu">
                                        <i class="f7-icons icon-menu-asset size-18"></i>
                                    </a>`;

                        ret += `  <a href="#" class="item-link item-content">
                                    <div class="item-inner">
                                        <div class="item-title-row">
                                            <div class="item-title text-transform-uppercase">${POSINFOASSETLIST[item.IMEI]?.Name || item.IMEI}</div>
                                            <div class="item-after"><i class="f7-icons icon-menu-asset fake-icon"></i></div>
                                        </div>
                                        <div class="item-text">
                                          <div class="row no-gap">
                                            <div class="col-50 margin-top-half">
                                              <i class="f7-icons size-16 icon-other-remove text-color-lightgray vertical-align-middle"></i>
                                              <span class="size-12 vertical-align-middle margin-left-half text-color-black">${ item.EndTimeLocal }</span>
                                            </div>
                                            <div class="col-50 margin-top-half">
                                              <i class="f7-icons size-16 icon-number text-color-lightgray vertical-align-middle"></i>
                                              <span class="size-12 vertical-align-middle margin-left-half text-color-black">${ item.Code }</span>
                                            </div>

                                          </div>
                                        </div>
                                    </div>
                                </a>
                            </li>`;
                        return ret;
                    },
                    emptyTemplate: `<li class="item-content">${LANGUAGE.COM_MSG139}</li>`
                });

                self.$setState({
                    isMyAssetsLoaded: true
                });
                //self.initSearchMyAssets();
            },
            initSearchMyAssets: function () {
                let self = this;

                self.SearchbarMyAssets = self.$app.searchbar.create({
                    el: self.$el.find('.searchbar-shared-assets-my'),
                    searchContainer: self.$el.find('.myAssetsList'),
                    searchIn: '.item-title',
                    notFoudEl: self.$el.find('.searchbar-not-found'),
                    backdrop: false
                });

            },
            updateMySharedAssetList(){
                var self = this;

                self.$app.methods.getMySharedAssetList()
                  .then(list => {
                      self.VirtualListMyAssets.replaceAllItems(list)
                  })
            },
            stopSharingMyAsset(imei){
                var self = this;
                self.$app.dialog.confirm(LANGUAGE.SHARE_ASSETS_MSG019, LANGUAGE.COM_MSG064, function (){
                    self.$app.preloader.show();
                    self.$app.request.post(API_URL.STOP_SHARE_ASSET, {
                        MajorToken: self.$app.data.MajorToken,
                        imei: imei
                    }, function (result) {
                            self.$app.preloader.hide();
                          if(result.MajorCode === '000') {
                              self.updateMySharedAssetList()
                              self.$app.methods.customDialog({text: LANGUAGE.SHARE_ASSETS_MSG022})
                          }else{
                              self.$app.dialog.alert(LANGUAGE.PROMPT_MSG023 + `<br>MajorCode: ${result.MajorCode}<br>MinorCode: ${result.MinorCode}`);
                          }
                        },
                          function (xhr, status) {
                              console.log(xhr);
                              console.log(status);
                              self.$app.preloader.hide();
                          },
                          'json');
                })

            },
            extendExpiryDate: function (code){
                var self = this;
                self.$app.dialog.prompt(LANGUAGE.SHARE_ASSETS_MSG024, LANGUAGE.SHARE_ASSETS_MSG023, function(value){
                    //console.log(value)
                    value = parseInt(value.trim())
                    if(!value){
                        self.$app.methods.customDialog({title: LANGUAGE.PROMPT_MSG100, text: LANGUAGE.SHARE_ASSETS_MSG025});
                        return
                    }
                    self.$app.preloader.show();
                    self.$app.request.post(API_URL.EDIT_ASSET_SHARE_CODE, {
                        MajorToken: self.$app.data.MajorToken,
                        //MinorToken: self.$app.data.MinorToken,
                        code: code,
                        days: value,
                    }, function (result) {
                          self.$app.preloader.hide();
                          if(result.MajorCode === '000') {
                              self.$app.methods.customDialog({text: LANGUAGE.SHARE_ASSETS_MSG026})
                              self.updateMySharedAssetList()

                          }else{
                              self.$app.dialog.alert(LANGUAGE.PROMPT_MSG023 + `<br>MajorCode: ${result.MajorCode}<br>MinorCode: ${result.MinorCode}`);
                          }
                      },
                        function (xhr, status) {
                            console.log(xhr);
                            console.log(status);
                            self.$app.preloader.hide();
                        },
                        'json');
                }, function (){
                    console.log('canceled')
                }, 30)
            },

            initListSubscribedAssetsList: function (assetList) {
                let self = this;
                console.log(assetList)
                let listEl = self.$el.find('.subscribedAssetsList');

                self.VirtualListSubscribed = self.$app.virtualList.create({
                    el: listEl,
                    items: assetList || [],
                    //cache: false,
                    searchAll: function (query, items) {
                        let found = [];
                        for (let i = 0; i < items.length; i++) {
                            if (items[i].Name.toLowerCase().indexOf(query.toLowerCase()) >= 0 ||
                              items[i].IMEI.toLowerCase().indexOf(query.toLowerCase()) >= 0 ||
                              query.trim() === ''
                            ){
                                found.push(i);
                            }
                        }
                        return found; //return array with mathced indexes
                    },
                    height: function (item) {
                        return self.$app.theme === 'ios' ? 45 : 53
                    },
                    renderItem: function (item, index) {
                        let ret = `
                            <li data-index="${index}">`;

                        ret += `  <a href="#" class="link color-custom ripple-color-red item-menu-button bigger-touch-area subscribedAssetsMenu">
                                        <i class="f7-icons icon-menu-asset size-18"></i>
                                    </a>`;

                        ret += `  <a href="#" class="item-link item-content">
                                    <div class="item-inner">
                                        <div class="item-title-row">
                                            <div class="item-title text-transform-uppercase">${item.Name || item.IMEI}</div>
                                            <div class="item-after"><i class="f7-icons icon-menu-asset fake-icon"></i></div>
                                        </div>

                                    </div>
                                </a>
                            </li>`;
                        return ret;
                    },
                    emptyTemplate: `<li class="item-content">${LANGUAGE.COM_MSG139}</li>`
                });

                self.$setState({
                    isSubscribedLoaded: true
                });
                //self.initSearchSubscribed();
            },
            initSearchSubscribed: function () {
                let self = this;
                self.SearchbarSubscribed = self.$app.searchbar.create({
                    el: self.$el.find('.searchbar-shared-assets-subscribed'),
                    searchContainer: self.$el.find('.subscribedAssetsList'),
                    searchIn: '.item-title',
                    notFoudEl: self.$el.find('.searchbar-not-found'),
                    backdrop: false
                });

            },
            updateSubscribedAssetList(){
                var self = this;

                self.$app.methods.getSubscribedAssetList()
                  .then(list => {
                      self.VirtualListSubscribed.replaceAllItems(list)
                  })
            },
            openSubscribeCodeDialog(){
                var self = this;
                self.$app.dialog.prompt(LANGUAGE.SHARE_ASSETS_MSG013, LANGUAGE.SHARE_ASSETS_MSG014, function(value){
                    //console.log(value)
                    value = value.trim()
                    if(!value){
                        self.$app.methods.customDialog({title: LANGUAGE.PROMPT_MSG100, text: LANGUAGE.SHARE_ASSETS_MSG015});
                        return
                    }
                    //self.$app.preloader.show();
                    self.$app.progressbar.show();
                    self.$app.request.post(API_URL.SUBSCRIBE_TO_ASSET_SHARE_CODE, {
                        MajorToken: self.$app.data.MajorToken,
                        //MinorToken: self.$app.data.MinorToken,
                        code: value
                    }, function (result) {
                              if(result.MajorCode === '000') {

                                  self.updateSubscribedAssetList()
                                  self.$app.methods.reLogin(function (){
                                      self.$app.progressbar.hide();
                                      self.$app.dialog.alert(LANGUAGE.SHARE_ASSETS_MSG017)
                                  })
                                  /*self.$app.dialog.alert(LANGUAGE.SHARE_ASSETS_MSG017 + '<br>' + LANGUAGE.SHARE_ASSETS_MSG029, function(){
                                      self.$app.methods.logout();
                                      leftView.router.back();
                                  });*/
                              }else{
                                  self.$app.methods.customDialog({title: LANGUAGE.PROMPT_MSG100, text: LANGUAGE.PROMPT_MSG023});
                                //  self.$app.dialog.alert(LANGUAGE.PROMPT_MSG023);
                                  self.$app.progressbar.hide();
                              }
                          },
                            function (xhr, status) {
                                console.log(xhr);
                                console.log(status);
                                self.$app.preloader.hide();
                            },
                            'json');
                }, function (){
                    console.log('canceled')
                }, '')
            },
            unsubscribeFromAsset(imei){
                var self = this;
                self.$app.dialog.confirm(LANGUAGE.SHARE_ASSETS_MSG020, LANGUAGE.SHARE_ASSETS_MSG018, function (){
                    self.$app.progressbar.show();
                    self.$app.request.post(API_URL.UNSUBSCRIBE_FROM_ASSET_SHARE_CODE, {
                        MajorToken: self.$app.data.MajorToken,
                        imei: imei
                    }, function (result) {
                          if(result.MajorCode === '000') {
                              self.$app.preloader.hide();
                              self.updateSubscribedAssetList()
                              self.$app.methods.reLogin(function (){
                                  self.$app.progressbar.hide();
                                  self.$app.dialog.alert(LANGUAGE.SHARE_ASSETS_MSG021)
                              })
                              /*self.$app.dialog.alert(LANGUAGE.SHARE_ASSETS_MSG021 + '<br>' + LANGUAGE.SHARE_ASSETS_MSG029, function(){
                                  self.$app.methods.logout();
                                  leftView.router.back();
                              });*/
                          }else{
                              self.$app.dialog.alert(LANGUAGE.PROMPT_MSG023 + `<br>MajorCode: ${result.MajorCode}<br>MinorCode: ${result.MinorCode}`);
                          }
                      },
                        function (xhr, status) {
                            console.log(xhr);
                            console.log(status);
                            self.$app.preloader.hide();
                        },
                        'json');
                })
            },
        },

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

               /* var passwordForm = page.$pageEl.find('[name = "user-password-form"]');*/
                var tabsEl = page.$pageEl.find('.tab');
                var myAssetsListEl = page.$el.find('.myAssetsList');
                var subscribedAssetsListEl = page.$el.find('.subscribedAssetsList');

                tabsEl.on('tab:show', function(){


                    if(this.id === "subscribed"){
                        self.SearchbarMyAssets.clear();
                    }else{
                        self.SearchbarSubscribed.clear();
                    }

                    self.$setState({
                        CurrentTab: this.id
                    }, ()=> {
                       /* self.SearchbarMyAssets.disable();
                        self.SearchbarSubscribed.disable();*/
                    });
                });

                self.initSearchMyAssets()
                self.initSearchSubscribed()
                self.$app.methods.getMySharedAssetList()
                  .then(list => self.initListMyAssetsList(list))

                self.$app.methods.getSubscribedAssetList()
                  .then(list => self.initListSubscribedAssetsList(list))

                myAssetsListEl.on('click', '.item-content', function () {
                    let index = $$(this).closest('li').data('index')

                    let isCopied = self.$app.methods.copyToClipboard(self.VirtualListMyAssets.items[index].Code)
                    if(isCopied){
                        self.$app.methods.showToast(LANGUAGE.SHARE_ASSETS_MSG012);
                    }
                })
                myAssetsListEl.on('click', '.myAssetsMenu', function () {
                    let index = $$(this).closest('li').data('index')
                    if(typeof(index) === 'undefined' ) return

                    self.$app.popover.create({
                        backdrop: false,
                        closeByOutsideClick: true,
                        targetEl: this,
                        content: `<div class="popover menu-popover">
                          <div class="popover-inner">
                            <div class="list assetMenuList">
                              <ul>
                                <li>
                                  <a href="#" class="item-link list-button popover-close viewDetails" >${ LANGUAGE.SHARE_ASSETS_MSG011 }</a>
                                </li>
                                <li>
                                  <a href="#" class="item-link list-button popover-close copyShareCode" >${ LANGUAGE.SHARE_ASSETS_MSG010 }</a>
                                </li>
                                <li>
                                  <a href="#" class="item-link list-button popover-close extendExpDate" >${ LANGUAGE.SHARE_ASSETS_MSG023 }</a>
                                </li>
                                <li>
                                  <a href="#" class="item-link list-button popover-close remove color-red" >${ LANGUAGE.COM_MSG138 }</a>
                                </li>
                              </ul>
                            </div>
                          </div>
                          </div>`,
                        on: {
                            open: function (popover) {
                                popover.$el.on('click', '.viewDetails', function(){
                                    leftView.router.navigate({
                                        name: 'shared-assets-view',
                                    }, {
                                        context: self.VirtualListMyAssets.items[index]
                                    })
                                })
                                popover.$el.on('click', '.copyShareCode', function(){
                                    let isCopied = self.$app.methods.copyToClipboard(self.VirtualListMyAssets.items[index].Code)
                                    if(isCopied){
                                        self.$app.methods.showToast(LANGUAGE.SHARE_ASSETS_MSG012);
                                    }
                                })
                                popover.$el.on('click', '.extendExpDate', function(){
                                    self.extendExpiryDate(self.VirtualListMyAssets.items[index].Code)
                                })
                                popover.$el.on('click', '.remove', function(){
                                    self.stopSharingMyAsset(self.VirtualListMyAssets.items[index].IMEI)
                                })

                            },
                            closed: function(popover){
                                popover.$el.off('click')
                                popover.destroy();
                            }
                        }
                    }).open();
                })


                subscribedAssetsListEl.on('click', '.item-content, .subscribedAssetsMenu', function () {
                    let index = $$(this).closest('li').data('index')
                    if(typeof(index) === 'undefined' ) return

                    self.$app.popover.create({
                        backdrop: false,
                        closeByOutsideClick: true,
                        targetEl: this,
                        content: `<div class="popover menu-popover">
                          <div class="popover-inner">
                            <div class="list assetMenuList">
                              <ul>
                                <li>
                                  <a href="#" class="item-link list-button popover-close unsubscribe" >${ LANGUAGE.SHARE_ASSETS_MSG018 }</a>
                                </li>

                              </ul>
                            </div>
                          </div>
                          </div>`,
                        on: {
                            open: function (popover) {
                                popover.$el.on('click', '.unsubscribe', function(){
                                    self.unsubscribeFromAsset(self.VirtualListSubscribed.items[index].IMEI)
                                })

                            },
                            closed: function(popover){
                                popover.$el.off('click')
                                popover.destroy();
                            }
                        }
                    }).open();
                })
            },
            pageBeforeRemove: function () {
                /*if (this.Searchbar){
                    this.Searchbar.destroy();
                }*/
                if (this.VirtualListMyAssets){
                    this.VirtualListMyAssets.destroy();
                }
                if (this.VirtualListSubscribed){
                    this.VirtualListSubscribed.destroy();
                }
                if (this.SearchbarMyAssets){
                    this.SearchbarMyAssets.destroy();
                }
                if (this.SearchbarSubscribed){
                    this.SearchbarSubscribed.destroy();
                }
            }

        }
    };
</script>
