<template>
  <card class="card-user" style="max-height:100%">

<br>
      <div class="author">
        <img class="avatar border-white" src="@/assets/img/docker.png" alt="...">
      </div>

  <v-wait for="myRunInstancetutormybuild">
    <template slot="waiting">
      <div>
        <img src="@/assets/loading.gif" />
        Enter Lab_room...
      </div>
    </template>
  </v-wait>

          <div class="row text-center">
            <div class="col-12">
              <b>Select a <span class="text-info"> Base image</span></b>
            </div>
          </div>

<br>




  <div class="input-group input-group-sm sm-3">
  </div>

		<div class="input-group input-group-sm sm-3">
				<button 
					class="btn btn-outline-success btn-sm" 
					round
					type="button"
					@click="setFilter">
					Refresh Table</button>
					
			<input type="text" 
				class="form-control" 
				aria-label="Small" aria-describedby="inputGroup-sizing-sm"
				placeholder="Search"
				v-model="searchFor"
				@keyup.enter="setFilter"
				>
					
			<div class="input-group-append">
				<button 
					class="btn btn-outline-primary" 
					round
					type="button"
					@click="setFilter">
					Go</button>
			</div>
					
			<div class="input-group-append">
				<button class="btn btn-outline-secondary" 
					round
					type="button"
					@click="resetFilter">
					Reset</button>
			</div>
    </div>

		<div class="input-group-append"
      v-if="viewhybridoptions && heavy"
    >
    <p class="text-danger">{{ heavytext }}</p>
    </div>

		<div class="white h-100 flex-fixed-width-item"
			<vuetable id="idvuetablekeygmybuildservice1"
				ref="vuetable"
				:key="vuetablekeygmybuildservice1"
				:api-url='apiurl'
				:api-mode="true"
				:http-options="httpOptions"
				:fields="fields"
				:item-actions="itemActions"
				:sort-order="sortOrder"
				:show-sort-icons="true"
				:multi-sort="multiSort"
				:per-page="perpage"
				pagination-path="links.pagination"
				:pagination-component="paginationComponent"
				:append-params="moreParams"
				wrapper-class="vuetable-wrapper"
				loading-class="loading"
				detail-row-id="id"
        @vuetable:row-clicked="rowClicked" 
				@vuetable:pagination-data="onPaginationData"
				@vuetable:load-success="loadsuccess"
        @vuetable:load-error="onLoadError"
				:css="css.table"
				 >

        <div slot="actions" slot-scope="props">
          <div class="d-flex justify-content-center">
            <button
              class="ti-cloud-up btn  btn-sm"
              title="Select Base MicroService"
              round
              @click="onAction('upload-item', props.rowData, props.rowData._id)">
            </button>
          <button
            class="ti-info btn  btn-sm"
              title="MicroService Info"
            round
            @click="onAction('view-item', props.rowData, props.rowData._id)">
          </button>
				 </div>
				</div>
			</vuetable>
			<div class="vuetable-pagination ui basic segment grid">
				<vuetable-pagination-info 
					ref="paginationInfo"      
					:css="css.paginationInfo"
      		>
				</vuetable-pagination-info>
				<vuetable-pagination 
					:css="css.pagination"
					ref="pagination"
        	@vuetable-pagination:change-page="onChangePage"
      		>
				</vuetable-pagination>
			</div>
    </div>
   </b-container>
  </card>
</template>
<script>
import store from '@/store/index'
import {mapState, mapGetters, mapActions,dispatch} from 'vuex'
import Vue from 'vue'
import {Vuetable, VuetablePaginationDropdown} from 'vuetable-2'
import VuetablePaginationInfo from 'vuetable-2/src/components/VuetablePaginationInfo'
import VuetablePagination from 'vuetable-2/src/components/VuetablePagination'
import CssConfig from 'vuetable-2/src/components/VuetableCssConfig.js'
import card from '@/components/Card.vue'
import {ApiConfig} from "@/config/index";
import {ApiConfigWEB} from "@/config/index-web";

export default {
  components: {
      card,
	    Vuetable,
			VuetablePagination,
			VuetablePaginationInfo,
			VuetablePaginationDropdown
	},
  props: {
  },
  data() {
   return{
   testactionrowindex:[],  // downloaded          used in installed
   teststatusindex:[],     // status stop run     used in status
   testtest:[],             // up or down services
   testtestdir:[],             // install download or not service
	  hybridoptions: {
      'index':'',            
      'swarmlabname':'',            
      'size':'',            
      'port':''            
    },
    viewhybridoptions: false,
    heavy: false,
    heavytext: '',
    customedit: false,
    custommenouopen: false,
    custommenou: false,
    custom: {
			'os':'',
			'sh':''
    },
    customostext: '',
    customshtext: '',
    up_name:'',
    swarmlab:{},
	  playbookInfo: {},
    token: '',
	  playbook: {
			'title':'',
			'name':'',
			'description':''
		},
			container:{
				name:'',
				view:0
			},
			pipeline:{},
 		selected: 'hybrid',
    options: [
      { text: 'Packages', value: 'packages' },
      { text: 'Images', value: 'images' },
      { text: 'Scripts', value: 'scripts' }
    ],
		showModal: false,
		visibility: [],
	 	active:false,
    vuetablekeygmybuildservice1:0,
		vuetablekeygslot:0,
		fielddata:{},
    fields: [
      {
        name: 'swarmlabname',
        title: '<span class="orange"></span>Base Image',
        sortField: 'swarmlabname',
        visible:true,
        dataClass: 'left aligned col-3 text-muted',
        width: '68%'
      },
      {
        name: '_id',
        title: '<span class="orange"></span>mongo',
        visible:false
      },
      {
        name: 'description',
        sortField: 'gitrepoCloneUrl',
        titleClass: 'center aligned',
        dataClass: 'left aligned w-25',
        visible:false,
        width: '15%'
      },
      {
        name: 'gitrepoFullName',
        sortField: 'gitrepoFullName',
        titleClass: 'center aligned',
        dataClass: 'left aligned w-25',
        visible:false,
        width: '15%'
      },
      {
          name: '__slot:actions',   // <----
          title: 'Actions',
          titleClass: 'col text-center',
          dataClass: 'center aligned',
          visible:false,
          width: '10%'
        },
    ],
		apiurl:ApiConfig.swarmlab_url_80+"/swarmlabhybridmicroservices",
		css: CssConfig,
    perpage: 8,
    searchFor: '',
		sortOrder: [{
				field: 'pipelinename',
				direction: 'asc'
		}],
    multiSort: true,
    paginationComponent: 'vuetable-pagination',
    currentpage:'1',
    currentpagepaginationData: {},
    dataselect:'',
    indexselect:'',
		itemActions: [
				{ name: 'view-item', label: '', icon: 'glyphicon glyphicon-zoom-in', class: 'btn btn-info', extra: {'title': 'View', 'data-toggle':"tooltip", 'data-placement': "left"} },
				{ name: 'edit-item', label: '', icon: 'glyphicon glyphicon-pencil', class: 'btn btn-warning', extra: {title: 'Edit', 'data-toggle':"tooltip", 'data-placement': "top"} },
				{ name: 'delete-item', label: '', icon: 'glyphicon glyphicon-remove', class: 'btn btn-danger', extra: {title: 'Delete', 'data-toggle':"tooltip", 'data-placement': "right" } }
		],
		moreParams: { 
				'filter':  '',
				'type':  'scripts'
			},
	 
		}
  },
	mounted() {
	},
	async created() {
    var url_string = window.location.href
    var url = new URL(url_string);
    this.token = url.searchParams.get("token");
		//await this.checkactionrowindexall()
    this.$root.$emit('hybrid_build_micro_service_menou')
    //console.log("token "+ this.token);
	},
    beforeDestroy () {
 },
  computed: {
		httpOptions() {
			var token = this.token
			    var p="headers: {Authorization: token}}"; //table props -> :http-options="httpOptions"
			    return {headers: {Authorization: 'Bearer ' + token}} //table props -> :http-options="httpOptions"
	  },

	},

  methods: {
    async refreshVuetable() {
					this.vuetablekeygmybuildservice1 += 1
      },
		setFilter () {
				this.moreParams = {
						'filter':  this.searchFor,
						'type':    this.selected
				}
        Vue.nextTick( () => this.$refs.vuetable.refresh())
		},
		resetFilter () {
				this.moreParams = {}
				this.searchFor = ''
				this.moreParams = {
						'filter':  '',
						'type':    'scripts'
				}
        Vue.nextTick( () => this.refreshVuetableall())
		},
   onPaginationData (paginationData) {
      this.$refs.pagination.setPaginationData(paginationData)
			this.$refs.paginationInfo.setPaginationData(paginationData) 
      this.currentpagepaginationData = paginationData
    },
    onChangePage (page) {
      this.currentpage = page
      this.$refs.vuetable.changePage(page)
    },
    editRow(rowData) {
      alert("You clicked edit on"+ JSON.stringify(rowData));
		},
    async onAction (action, data, index) {
			if(action == 'view-item' ){
          this.swarmlab=data
          var container=this.swarmlab
          var res = await store.dispatch('pipelineLLO/getswarmlabmicroserviceinfo', container.swarmlabname)

          var swarmlab1=JSON.stringify(res.data.swarmlab, null ,2)
          var swarmlab1info=JSON.stringify(res.data.swarmlabinfo, null ,2)
          var swarmlab1info=res.data.swarmlabinfo
          var description='<div style="height: 250px; overflow-y: scroll;"><p><pre><code class="codeblock">'+swarmlab1+'</code></pre></p></div>'
          if(res.data.error25=="ok"){
                var winfo=''
                var info='<h5>Swarmlab Service <a href="'+swarmlab1info+'" target="_blank" >Info</a></h5>(Open page in new window)'
                this.$swal({
                  type: 'info',
                  html: info+winfo,
                  showCloseButton: true,
                  showLoaderOnConfirm: false,
                  allowOutsideClick: false,
                  showLoaderOnConfirm: false,
                  reverseButtons: true,
                  focusCancel: true
                })
            }

			}else if(action == 'upload-item' ){
			//	var log = await store.dispatch("pipelineLLO/getmyservices",{
			//		token:this.token,
			//		service:data.swarmlabname
			//	})
        //console.log(log)
        this.swarmlab=data
          var service = {
              data:    data
       //       log:    log
            }
        this.$root.$emit('hybrid_build_micro_service', service)
			}
    },
    async refreshVuetable() {
		    //await this.checkactionrowindexall()
					this.vuetablekeygslot += 1
      },
		playbookinfoShow(value) {
				return this.visibility[value]=true
		},
		playbookinfo(value) {
				return this.playbookInfo=value
		},
		rowClicked(row, event) {
			console.log(row)
			this.onAction('upload-item', row, row._id)
    /*
			return {
				html: true,
				title: () => { return 'Hello <b>Popover:</b> ' + (++this.counter) },
				content: () => { return 'The date is:<br><em>' + new Date() + '</em>' }
			}
     */
		},
		loadsuccess(response) {
				var data = response.data.data
				this.fielddata=data
				var n = data.length
				n=n-1
			},
      onLoadError(payload) {
        if(payload.response.status == '401'){
          window.location.href = 'https://api-login.swarmlab.io:8089';
          Vue.nextTick( () => window.location.href = 'https://api-login.swarmlab.io:8089')
        }
      }


  },


  actions: {


	}

};
</script>
<style>

#idvuetablekeygmybuildservice1 tr td {
    border-left: 0px solid;
    border-right: 0px solid;
    padding: 0px;
}


#idvuetablekeygmybuildservice1 tr td {
  color: #2185d0;
  cursor: pointer;
}

.flex-fixed-width-item {
    flex: 0 0 100px;
		}
.modalinfo {
  z-index: 10000000 !important;
	position:fixed;
}
/* a container with flex-direction column */

.vue-notifyjs.notifications{
  .alert{
   z-index: 100;
  }
  .list-move {
    transition: transform 0.3s, opacity 0.4s;
  }
  .list-item {
    display: inline-block;
    margin-right: 10px;

  }
  .list-enter-active {
    transition: transform 0.2s ease-in, opacity 0.4s ease-in;
  }
  .list-leave-active {
    transition: transform 1s ease-out, opacity 0.4s ease-out;
  }

  .list-enter {
    opacity: 0;
    transform: scale(1.1);

  }
  .list-leave-to {
    opacity: 0;
    transform: scale(1.2, 0.7);
  }
}

pre {
  //background-color: rgb(255, 247, 229);
  background-color: #eff0f1;
	  border: 1px solid blue;
		  //white-space: pre-line;
			}

</style>
