<template>
  <card class="card-user" style="max-height:100%">
      <div class="author">
        <img class="avatar border-white" src="@/assets/img/docker.png" alt="...">
      </div>

      <b-container fluid class="bv-example-row">


  <v-wait for="myRunInstancetutor">
    <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>Swarmlab <span class="text-info">Users MicroServices</span> Deploy - Local </b>
            </div>
          </div>

<br>


		<div class="input-group input-group-sm sm-3">
					
			<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="row"
      v-if="viewhybridoptions"
    >
      <b-col  class="text-center" cols="12" sm="12"  md="12">
                <span>
                <b>Lab Service Options</b>
                </span>
      </b-col>
    </div>

		<div class="input-group-append"
      v-if="viewhybridoptions"
    >
				<button class="btn btn-outline-secondary" 
					round
					type="button"
        >
				Instances </button>
			<input type="text" 
				class="form-control text-info" 
				aria-label="Small" aria-describedby="inputGroup-sizing-sm"
				placeholder="Number of Instances"
        disabled
				v-model="up_name"
				>
        <!--
				<button class="btn btn-outline-secondary" 
					round
					type="button"
        >
				Port</button>
			<input type="text" 
				class="form-control" 
				aria-label="Small" aria-describedby="inputGroup-sizing-sm"
				placeholder="Expose Port"
        disabled
				v-model="hybridoptions.port"
				>
        <div  class="text-info">{{ up_name }}</div>
        -->

				<button class="btn btn-outline-info" 
           v-if="viewhybridoptions"
					round
					type="button"
				  @click="backup"
        >
				Backup</button>
				<button class="btn btn-outline-dark" 
           v-if="viewhybridoptions"
					round
					type="button"
				  @click="backupview"
        >
				BackupView</button>

				<button class="btn btn-outline-primary" 
           v-if="viewhybridoptions && customedit && custommenouopen != true"
					round
					type="button"
				  @click="setcustom"
        >
				Custom</button>
				<button class="btn btn-outline-secondary" 
          v-if="viewhybridoptions && customedit && custommenouopen === true"
					round
          disabled
					type="button"
				  @click="setcustom"
        >
				Custom:</button>

				<button class="btn btn-outline-warning" 
           v-if="viewhybridoptions && customedit && custommenouopen"
					round
					type="button"
				  @click="setcustomcancel"
        >
				Cancel</button>
				<button class="btn btn-outline-info" 
           v-if="viewhybridoptions && customedit && custommenouopen"
					round
					type="button"
				  @click="setcustomsave"
        >
				Save</button>

				<button class="btn btn-outline-success" 
					round
					type="button"
				  @click="setHybridoptions"
        >
				Up</button>
    </div>

		<div class="input-group-append"
      v-if="viewhybridoptions && custommenou"
    >

    <div class="row"
      <b-col  class="text-center" cols="5" sm="5"  md="5">
        <div class="form-group">
          <label for="custompackages" class="text-dark">Add Extrapackages  <br>
          <span class="text-success">
          {{ customostext }}
          </span >
          </label>
          <textarea class="form-control" id="custompackages" rows="8"
				      v-model="custom.os"
          >
          {{ custom.os }}
          </textarea>
        </div>
      </b-col>
      <b-col  class="text-center" cols="7" sm="7"  md="7">
        <div class="form-group">
          <label for="customshell" class="text-dark">Custom sh script <br>
          <span class="text-success">
          {{ customshtext }}
          </span >
          </label>
          <textarea class="form-control" id="customshell" rows="8"
				      v-model="custom.sh"
          >
          {{ custom.sh }}
          </textarea>
        </div>
      </b-col>
    </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 
				ref="vuetable"
				:key="vuetablekeygusersservices"
				: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:pagination-data="onPaginationData"
				@vuetable:load-success="loadsuccess"
        @vuetable:load-error="onLoadError"
				:css="css.table"
				 >

        <div slot="actionsenabled" slot-scope="props">
          <div class="d-flex justify-content-center">
            <button 
              v-if="testtest[props.rowData.service] != props.rowData.service && testtestdir[props.rowData.service] == props.rowData.service && testtestdiruser[props.rowData.service] == props.rowData.user"
              class="ti-thumb-down btn btn-secondary btn-sm"
              title="Start Lab_Instance"
              round
              @click="onAction('run-item', props.rowData, props.rowData._id)"
              >
            </button>
            <button
              v-if="testtest[props.rowData.service] == props.rowData.service && testtestdir[props.rowData.service] == props.rowData.service && testtestdiruser[props.rowData.service] == props.rowData.user"
              class="ti-thumb-up btn btn-info btn-sm"
              title="Stop Lab_Instance"
              round
              @click="onAction('down-item', props.rowData, props.rowData._id)"
              >
            </button>
          </div>
        </div>
        <div slot="actionslocal" slot-scope="props" actionslocal
				:key="vuetablekeygslotcustom">
          <div class="d-flex justify-content-center">
            <button
              v-if="testtest[props.rowData.service] != props.rowData.service && testtestdir[props.rowData.service] == props.rowData.service"
              class="ti-trash btn btn-info btn-sm"
              title="Remove Lab_Instance"
              @click="onAction('rm-install', props.rowData, props.rowData._id)"
              round
              >
              {{ testtestdir[props.rowData.baseservice] }}
            </button>
          </div>
        </div>
        <div slot="actions" slot-scope="props">
          <div class="d-flex justify-content-center">
            <button
              class="ti-cloud-down btn btn-outline-secondary btn-sm"
              title="Download Lab_Instance"
              round
              @click="onAction('run-install', props.rowData, props.rowData._id)">
            </button>
          <button
            class="ti-info btn btn-outline-secondary btn-sm"
              title="Lab_Instance 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
   testtestdiruser:[],             // 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,
		vuetablekeygusersservices:0,
		vuetablekeygslotcustom:0,
		fielddata:{},
    fields: [
      {
        name: 'service',
        title: '<span class="orange"></span>Name',
        sortField: 'service',
        visible:true,
        dataClass: 'left aligned col-3',
        width: '30%'
      },
      {
        name: '_id',
        title: '<span class="orange"></span>mongo',
        visible:false
      },
      {
        name: 'readme',
        title: '<span class="orange"></span>Info',
        titleClass: 'center aligned',
        dataClass: 'left aligned w-25',
        visible:true,
        width: '35%'
      },
      {
        name: 'user',
        title: '<span class="orange"></span>User',
        sortField: 'user',
        titleClass: 'center aligned',
        dataClass: 'left aligned w-25',
        visible:true,
        width: '10%',
        callback: function(value) {
          if (value) {
              var v = value.split('@')
              if (v[0]) {
                var vv = '<p class="text-info">' + v[0] +'</p>'
                return vv
              } else {
                var vv = '<p class="text-info"></p>'
                return vv
              }
          }else{
                return value
          }
        }
      },
      {
        name: 'gitrepo',
        title: '<span class="orange"></span>User repo',
        sortField: 'gitrepo',
        titleClass: 'center aligned',
        dataClass: 'left aligned w-25',
        visible:true,
        width: '30%'
      },
      {
          name: '__slot:actionsenabled',   // <----
          title: 'Status',
          titleClass: 'center',
          dataClass: 'center aligned',
          width: '5%'
        },
      {
          name: '__slot:actionslocal',   // <----
          title: 'Installed',
          titleClass: 'center',
          dataClass: 'center aligned',
          width: '5%'
        },
      {
          name: '__slot:actions',   // <----
          title: 'Download',
          titleClass: 'col text-center',
          dataClass: 'center aligned',
          width: '10%'
        },
    ],
		apiurl:ApiConfig.swarmlab_url_80+"/swarmlabhybridmymicroservicesall",
		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() {
		this.$root.$on('hybrid_build_micro_service_menou_refreshtable', ()  => {
        this.refreshVuetable()
        //this.refreshVuetableall()
    })
		this.$root.$on('hybrid_refresh_availableservices', () => {
        //Vue.nextTick( () => this.$refs.vuetable.refresh())
        Vue.nextTick( () => this.refreshVuetable())
		})
    //refresh from socket mytable 
		this.$root.$on('hybrid_refresh_table', (v) => {
			  this.$nextTick(function () {
            //Vue.nextTick( () => this.$refs.vuetable.refresh())
            this.refreshVuetable()
            this.viewhybridoptions = false
			  })
		})
	},
	async created() {
    var url_string = window.location.href
    var url = new URL(url_string);
    this.token = url.searchParams.get("token");
		//await this.checkactionrowindexall()
    await this.refreshVuetable()
    //console.log("token "+ this.token);
	},
    beforeDestroy () {
		this.$root.$off('hybrid_refresh_availableservices')
		this.$root.$off('hybrid_build_micro_service_menou_refreshtable')
		this.$root.$off('hybrid_refresh_table')
 },
  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: {
   onError (type,description) {
                    var winfo=description
                    var info='<h5>Bootstrap '+type+'</h5>'
                    this.$swal({
                      type: type,
                      html: info+winfo,
                      showCloseButton: true,
                      showLoaderOnConfirm: false,
                      allowOutsideClick: false,
                      cancelButtonText: 'No, cancel!',
                      showCancelButton: false,
                      showLoaderOnConfirm: false,
                      reverseButtons: true,
                      focusCancel: true,
                      confirmButtonText: 'Ok!'
                      })
    },
		async checkactionrowindexall(){
          var obj = {}
          obj.token = this.token
          obj.instance = 'info'
          var res1 = await store.dispatch('pipelineLLO/getservicesstatusall', obj)
          if(res1.data.data){
            var al =   res1.data.data.length;
            for (var arrayIndex in this.testtest) {
                Vue.delete(this.testtest, this.testtest[arrayIndex])
            }
            for (let index = 0; index < al; ++index) {
                var el  = res1.data.data[index];
            console.log('resall-run--> '+JSON.stringify(el))
/*
                  var atmp1a = el.split('@');
                  if(atmp1a[1]){
                    console.log('resall---> atmp1a a '+JSON.stringify(atmp1a))
                    var atmp2a = atmp1a[1].split('_');
                    console.log('resall---> atmp1a '+JSON.stringify(atmp1a))
                    console.log('resall---> atmp2a '+JSON.stringify(atmp2a[1]))
                    Vue.set(this.testtest, atmp2a[1], atmp2a[1])
                  }
*/
                var el1 = el.Names.split('_');
                let indexiuser = el1[0].lastIndexOf('-');
                indexiuser++
                var restuser = el1[0].substring(indexiuser) 
                console.log(restuser)
                //Vue.set(this.testtest, el1[0], el1[0])
                Vue.set(this.testtest, restuser, restuser)
                console.log(this.testtest)

            }
          }
          var res2 = await store.dispatch('pipelineLLO/getservicesinfoallcustom', obj)
          if(res2.data.data){
            for (var arrayIndex in this.testtestdir) {
                Vue.delete(this.testtestdir, this.testtestdir[arrayIndex])
            }
          console.log('elnames user all ' + JSON.stringify(this.hybridoptions))
            var all =   res2.data.data.length;
            for (let index = 0; index < all; ++index) {
                var el1a  = res2.data.data[index];
                console.log('elnames1' + el1a)
                // for multiuser must xx = false
                var xx = false
                if(xx){
                  var struser = `${this.hybridoptions.user}_`
                  var strbase = `_${this.hybridoptions.baseservice}`
                  console.log('elnames user  ' + struser)

                  var sRegExInput = new RegExp(struser, 'g');    
                  var a = el1a.replace(sRegExInput ,'');
                  var sRegExInput1 = new RegExp(strbase, 'g');    
                  var a1 = a.replace(sRegExInput1 ,'');

                  //var a = el1a.replace('struser',"");
                  console.log('elnames -a1 ' + a1)
                  console.log('elnames -a ' + a)
                  Vue.set(this.testtestdir, a1, a1)
                }else{
                  var atmp1 = el1a.split('@');
                  if(atmp1[1]){
                    console.log('resall---> atmp1 a '+JSON.stringify(atmp1))
                    var atmp2 = atmp1[1].split('_');
                    console.log('resall---> atmp1 '+JSON.stringify(atmp1))
                    console.log('resall---> atmp2 '+JSON.stringify(atmp2[1]))
                    console.log('resall---> 2222 '+JSON.stringify(atmp2))
                    Vue.set(this.testtestdir, atmp2[1], atmp2[1])
                    var servicecustomuser = `${atmp1[0]}@${atmp2[0]}`
                    Vue.set(this.testtestdiruser, atmp2[1], servicecustomuser)
                console.log(this.testtestdir)
                console.log(this.testtestdiruser)
                    //Vue.set(this.testtestuser, el1[0], el1[0])
                  }

                }
            }
          }
            console.log('resall1---> '+JSON.stringify(res2.data.data))
            console.log('resall--->> '+JSON.stringify(this.testtestdir))
          //console.log(this.testtestdir)
    },
		setFilter () {
				this.moreParams = {
						'filter':  this.searchFor,
						'type':    this.selected
				}
        Vue.nextTick( () => this.$refs.vuetable.refresh())
        //Vue.nextTick( () => this.refreshVuetable())
        //this.refreshVuetable()
		},
		resetFilter () {
				this.moreParams = {}
				this.searchFor = ''
				this.moreParams = {
						'filter':  '',
						'type':    'scripts'
				}
        //Vue.nextTick( () => this.$refs.vuetable.refresh())
        Vue.nextTick( () => this.refreshVuetableall())
        //this.refreshVuetable()
		},
   onPaginationData (paginationData) {
      this.$refs.pagination.setPaginationData(paginationData)
			this.$refs.paginationInfo.setPaginationData(paginationData) 
      this.currentpagepaginationData = paginationData
        //console.log('inf git 0 '+ JSON.stringify(paginationData))
        //console.log('inf git 1 '+ JSON.stringify(this.fielddata[1]))
    },
    onChangePage (page) {
        this.resetcustom()
      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.readme
        console.log('inf '+ JSON.stringify(data))
        //console.log('infi '+ JSON.stringify(index))

          var description='<div style="height: 250px; overflow-y: scroll;"><p>'+container+'</p></div>'
                var info='<h5>Service Info</h5>'
                    info += description
                this.$swal({
                  type: 'info',
                  html: info,
                  icon: 'info',
                  showCloseButton: true,
                  showLoaderOnConfirm: false,
                  allowOutsideClick: false,
                  showLoaderOnConfirm: false,
                  reverseButtons: true,
                  focusCancel: true
                })


			}else if(action == 'delete-item' ){
				this.$swal({
					type: 'info',
					html: info+winfo,
					showCloseButton: true,
					showLoaderOnConfirm: false,
					allowOutsideClick: false,
					 cancelButtonText: 'No, cancel!',
					showCancelButton: true,
					showLoaderOnConfirm: false,
					reverseButtons: true,
					focusCancel: true,
					confirmButtonText: 'Yes, Delete it!'
					})
        //Vue.nextTick( () => this.$refs.vuetable.refresh())
        Vue.nextTick( () => this.refreshVuetable())
        //this.refreshVuetable()
			}else if(action == 'rm-install' ){
        this.resetcustom()
         this.hybridoptions.swarmlabname = data.swarmlabname
         this.$wait.start('myRunInstancetutor');
         //console.log(this.hybridoptions.swarmlabname)
         var res = await store.dispatch('pipelineLLO/rmswarmlablocal', this.hybridoptions.swarmlabname)
         this.$wait.end('myRunInstancetutor');
                var obj = {}
                obj.token = this.token
                obj.instance = data.swarmlabname
                //check if exists
                var res2 = await store.dispatch('pipelineLLO/getservicesinfo', obj)
                if(res2.data.data == 'yes'){
                  if(res2.data.data == 'yes'){
                    var winfo='<h6 class="text-warning"> swarmlab encountered a problem while deleting your labroom files. <br> This propably means that you have created some files while operating the labroom. <br> To remove those files please run the following command as root.  </h6> <h5><i>Copy-and-run-command </i></h5><br> ' 
                    winfo += '<span class="text-success">sudo rm -rf '+res.data.path+'/instance/'+data.swarmlabname+'  </span><br><br>'
                    winfo += '<span class="text-secondary"> You can back up content using: </span><br>'
                    winfo += '<span class="text-warning">sudo tar -zcvf /home/\$USER/swarmlabbackup_'+data.swarmlabname+'.tar.gz '+res.data.path+'/instance/'+data.swarmlabname+'  </span>'
                    var info='<h5>Labroom remove</h5>'
                    this.$swal({
                      type: 'info',
                      html: info+winfo,
                      icon: 'info',
                      showCloseButton: true,
                      showLoaderOnConfirm: false,
                      allowOutsideClick: false,
                      cancelButtonText: 'No, cancel!',
                      showCancelButton: false,
                      showLoaderOnConfirm: false,
                      reverseButtons: true,
                      focusCancel: true,
                      confirmButtonText: 'Ok!'
                      })
                  }
                }
        this.refreshVuetable()
        this.$root.$emit('hybrid_refresh_info_deploy_local')
			}else if(action == 'run-install' ){
         this.$wait.start('myRunInstancetutor');
         this.hybridoptions.swarmlabname = data.swarmlabname
         this.hybridoptions.baseservice  = data.baseservice
         this.hybridoptions.service  = data.service
         this.hybridoptions.user  = data.user
         this.hybridoptions.index = index
        let value = {}
        value.swarmlabname = this.hybridoptions.swarmlabname
        value.baseservice      = this.hybridoptions.baseservice
        value.service      = this.hybridoptions.service
        value.user      = this.hybridoptions.user
        value.index = this.hybridoptions.index
        value.size = this.hybridoptions.size
        value.port = this.hybridoptions.port
          var res = await store.dispatch('pipelineLLO/getswarmlabmicroserviceinfo', value.baseservice)
          var swarmlab1info=res.data.swarmlabinfo
        value.git = swarmlab1info
        //console.log('inf git 0 '+ JSON.stringify(value.swarmlabname))
        //console.log('inf git 1 '+ JSON.stringify(res))
        //console.log('inf '+ JSON.stringify(value))
              var log = await store.dispatch("pipelineLLO/checkownercustom",{
                token:this.token,
                instance:this.hybridoptions.swarmlabname
                })

              for(var i = 0; i < ApiConfigWEB.length; i++) {
                var obWEB = ApiConfigWEB[i];

                //--------------
						    if(obWEB.name == this.hybridoptions.baseservice){
                    value.baseservicedata = obWEB
/*
                  if(obWEB.hasOwnProperty('large')){
                    if(obWEB.large != 'no'){
                    //  console.log(obWEB.large)
                      this.heavy = true
                      this.heavytext =  obWEB.large
                    }
                  }
*/
                }
              }




      	this.$root.$emit('hybrid_install_instance_custom', value)
         this.$wait.end('myRunInstancetutor');
        //Vue.nextTick( () => this.$refs.vuetable.refresh())
        this.refreshVuetable()

			}else if(action == 'run-item' ){
        this.resetcustom()
         this.hybridoptions.swarmlabname = data.swarmlabname
         this.hybridoptions.baseservice  = data.baseservice
         this.hybridoptions.packages  = data.packages
         this.hybridoptions.sh        = data.sh
         this.hybridoptions.rclocal   = data.rclocal
         this.hybridoptions.service  = data.service
         this.hybridoptions.user  = data.user
         this.hybridoptions.index = index

         this.hybridoptions.port1        = data.port1
         this.hybridoptions.url1         = data.url1
         this.hybridoptions.name1        = data.name1

         this.hybridoptions.port2        = data.port2
         this.hybridoptions.url2         = data.url2
         this.hybridoptions.name2        = data.name2

         this.hybridoptions.port3        = data.port3
         this.hybridoptions.url3         = data.url3
         this.hybridoptions.name3        = data.name3

        //this.custom.sh = ''

         this.heavy = false
         this.heavytext = ''

         this.up_name = data.swarmlabname

        console.log('RUN------------ '+ JSON.stringify(data))

      			var filtermicrosfot = `microservice-volatilitywindows`
            var grepmicrosoft = new RegExp(filtermicrosfot);

      			var filterju = `microservice-jupyter`
            var grepju = new RegExp(filterju);
						if(grepju.test(data.swarmlabname)){
              this.viewhybridoptions = false
              let value = {}
              value.swarmlabname = data.swarmlabname
              value.index = index
              value.size = this.hybridoptions.size
              value.port = this.hybridoptions.port
              this.$root.$emit('hybrid_start_instance', value)
              //Vue.set(this.testactionrowindex, value.swarmlabname, value.index)
              //Vue.set(this.testactionrowindex, value.index, value.swarmlabname)
						}else if(grepmicrosoft.test(data.swarmlabname)){
              this.viewhybridoptions = true
              this.heavy = true
              this.heavytext = 'Note that this image is somewhat heavy (~2GB) since they embed some of the kernel debug symbols for Microsoft Windows.  It can take some time to build the Instance'
              this.hybridoptions.swarmlabname = data.swarmlabname
              this.hybridoptions.index = index
						}else{
              this.viewhybridoptions = true
              this.hybridoptions.swarmlabname = data.swarmlabname
              this.hybridoptions.index = index
        //console.log('RUN base1 '+ JSON.stringify(data))
              for(var i = 0; i < ApiConfigWEB.length; i++) {
                var obWEB = ApiConfigWEB[i];

                //--------------
						    if(obWEB.name == data.baseservice){
                  if(obWEB.hasOwnProperty('large')){
                    if(obWEB.large != 'no'){
                    //  console.log(obWEB.large)
                      this.heavy = true
                      this.heavytext =  obWEB.large
                    }
                  }
                }
                // -------------------------
						    if(obWEB.name == data.baseservice){
                    this.hybridoptions.baseservicedata  = obWEB
        //console.log('RUN base '+ JSON.stringify(this.hybridoptions))
                  if(obWEB.hasOwnProperty('custom')){
                    if(obWEB.custom != 'no'){
                      console.log(obWEB.custom)
                      this.customedit = true
                      this.custom.os =  obWEB.customos
                      this.custom.sh =  obWEB.customsh
                      this.customostext =  obWEB.customostext
                      this.customshtext =  obWEB.customshtext
                    }
                  }
                }
                // -------------------------

              }
      /*
        console.log('RUN 1 '+ JSON.stringify(data.swarmlabname))
        // run on  mytable.vue
      	this.$root.$emit('hybrid_start_instance', data.swarmlabname)
        Vue.nextTick( () => this.$refs.vuetable.refresh())
        */
				}
        //Vue.nextTick( () => this.$refs.vuetable.reload())
        //EDO
        //this.refreshVuetable()
			}else if(action == 'down-item' ){
         this.up_name = ''
         this.hybridoptions = data
         this.hybridoptions.index = index
       var info = "Stop and remove containers, networks, images, and volumes"
       this.$swal({
          type: 'info',
          html: info,
          showCloseButton: true,
          showLoaderOnConfirm: false,
          allowOutsideClick: false,
          cancelButtonText: 'No, cancel!',
          showCancelButton: true,
          showLoaderOnConfirm: false,
          reverseButtons: true,
          focusCancel: false,
          confirmButtonText: 'Yes!'
          }).then((result)=> {
            this.rmAndClose(result);
          })

        //console.log('RUN 1 '+ JSON.stringify(data.swarmlabname))
        //Vue.nextTick( () => this.$refs.vuetable.refresh())
        //this.refreshVuetable()
			}
    },
		async rmAndClose(result){
        //console.log('value 1 '+ JSON.stringify(result))
        //console.log('value 1 '+ JSON.stringify(this.hybridoptions))
    		if (result.isConfirmed) {
					//console.log('yes')       
          // run on  mytable.vue
          var value = this.hybridoptions.swarmlabname
      	  //await this.$root.$emit('hybrid_stop_instance', value)
              var log = await store.dispatch("pipelineLLO/stopservicecustom",{
                token:this.token,
                instance:this.hybridoptions
                })
          //Vue.delete(this.testactionrowindex, this.hybridoptions.index)
          //console.log('down service '+ JSON.stringify(this.hybridoptions.index))
          //Vue.nextTick( () => this.$refs.vuetable.refresh())
          //console.log(log)
          this.refreshVuetable()
        }else  {
					console.log('no')       
        }
	  },
		async setcustomcancel(){
        this.custommenouopen = false
        this.custommenou = false
	  },
		async setcustomsave(){
        let value = {}
        value.swarmlabname = this.hybridoptions.swarmlabname
        var log = await store.dispatch("pipelineLLO/savecustom",{
          token:this.token,
          instance:this.hybridoptions.swarmlabname,
          package:this.custom.os,
          sh:this.custom.sh
          })
        this.custommenouopen = false
        this.custommenou = false
        console.log('chown ok '+ JSON.stringify(log.data))
	  },
		async setcustom(){
        let value = {}
        value.swarmlabname = this.hybridoptions.swarmlabname
        this.custommenouopen = true
        this.custommenou = true
        var log = await store.dispatch("pipelineLLO/getcustom",{
          token:this.token,
          instance:this.hybridoptions.swarmlabname
          })
          if(log.data.error === false){
           if(log.data.error_msg == 'nodir'){
              //console.log('chown reload')
                  var info=`<h5><b> Please redownload Microservice and try launching the module again </b><br> 
                  </h5>
    `
                this.$swal({
                  type: 'Info',
                  icon:'info',
                  html: info,
                  showCloseButton: true,
                  showLoaderOnConfirm: false,
                  allowOutsideClick: false,
                  cancelButtonText: 'No, cancel!',
                  showCancelButton: false,
                  showLoaderOnConfirm: false,
                  reverseButtons: true,
                  focusCancel: true,
                  confirmButtonText: 'Ok!'
                })
            }

           if(log.data.error_msg == 'ok'){
               if(log.data.extrapackagestext != ''){
                  //this.custom.os = log.data.extrapackagestext
                  Vue.set(this.custom, 'os', log.data.extrapackagestext)
                }
               if(log.data.extrashtext != ''){
                  //this.custom.sh = log.data.extrashtext
                  Vue.set(this.custom, 'sh', log.data.extrashtext)
                }
                console.log('chown extrapackages1 '+ JSON.stringify(this.custom.os))
                console.log('chown sh1 '+ JSON.stringify(this.custom.sh))
            }

          }else{
                  var info=`<h5><b> Please remove and download Microservice and try launching the module again </b><br> 
                  </h5>
    `
                this.$swal({
                  type: 'Info',
                  icon:'info',
                  html: info,
                  showCloseButton: true,
                  showLoaderOnConfirm: false,
                  allowOutsideClick: false,
                  cancelButtonText: 'No, cancel!',
                  showCancelButton: false,
                  showLoaderOnConfirm: false,
                  reverseButtons: true,
                  focusCancel: true,
                  confirmButtonText: 'Ok!'
                })
          }
         //console.log('chownlog '+ JSON.stringify(log))
         //console.log('chown extrapackages '+ JSON.stringify(this.custom.os))
         //console.log('chown sh '+ JSON.stringify(this.custom.sh))
	  },
		async backup(){
      var log = await store.dispatch("pipelineLLO/runbackupinstance",{
        token:this.token,
        instance: this.hybridoptions.swarmlabname
        })
	  },
		async backupview(){
                  var info=`<h5><b>Backups</b><br> 
                  <br>
    `
  info +='<p class="text-secondary">'
info +=' <b>Click on hyperlink opens Directory in new tab</b></p>'
 info +='<b> <a class="text-info" href="http://127.0.0.1:3383/" target="_blank">View Backups</a></b>'
 info +='<br>'
                this.$swal({
                  type: 'Info',
                  title: 'Info!',
                  icon:'info',
                  html: info,
                  showCloseButton: true,
                  showLoaderOnConfirm: false,
                  allowOutsideClick: false,
                  cancelButtonText: 'No, cancel!',
                  showCancelButton: false,
                  showLoaderOnConfirm: false,
                  reverseButtons: true,
                  focusCancel: true,
                  confirmButtonText: 'Ok!'
                })
	  },
		async setHybridoptions(){
        this.resetcustom()
        //console.log(JSON.stringify(data))
        //this.hybridoptions.os = data.os
        
        // run on  mytable.vue
        let value = {}
        value.swarmlabname = this.hybridoptions.swarmlabname
        value.index = this.hybridoptions.index
        value.size = this.hybridoptions.size
        value.port = this.hybridoptions.port
              var log = await store.dispatch("pipelineLLO/chowncustom",{
                token:this.token,
                user:this.hybridoptions.user,
                service:this.hybridoptions.service,
                baseservice:this.hybridoptions.baseservice
                })
              console.log('data '+ JSON.stringify(this.hybridoptions))
      	//this.$root.$emit('hybrid_start_instance_custom', value)
      	this.$root.$emit('hybrid_start_instance_custom', this.hybridoptions)
        //Vue.set(this.testactionrowindex, value.swarmlabname, value.index)
        //Vue.set(this.testactionrowindex, value.index, value.swarmlabname)
        //Vue.nextTick( () => this.$refs.vuetable.refresh())
        //Vue.nextTick( () => this.$refs.vuetable.refresh())
        this.refreshVuetable()

        //console.log('RUN 1 '+ JSON.stringify(this.hybridoptions))

		},
    async refreshVuetableall() {
			this.$nextTick(()=>{
					this.vuetablekeygusersservices += 1
				})
		},
    async resetcustom() {
        this.customedit = false
        this.custommenouopen = false
        this.custommenou = false
        this.custom.os = ''
        this.custom.sh = ''
		},
    async refreshVuetable() {
				//this.vuetablekeygusersservices += 1
        // EDO
        // echo ta data pou exei epilexei o user
        // kai etsi alazo se afta tin katastassi
        // afero ta $nextTick
        // kai allazo apo refresh edo se afto to action
        // refresh only status
          // ********* refresh slot einai i lissi  ***
        //this.dataselect=data
        //this.indexselect=index
        //console.log('error2a '+JSON.stringify(this.dataselect))
        //console.log('error2b '+JSON.stringify(this.indexselect))
        // render hangs
		    await this.checkactionrowindexall()
					this.vuetablekeygslotcustom += 1
          //des 
					//this.vuetablekeygusersservices += 1
				//})
      },
		playbookinfoShow(value) {
				return this.visibility[value]=true
		},
		playbookinfo(value) {
				return this.playbookInfo=value
		},
		rowClicked(row, event) {
			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) {
          /*
          //error2 "invalid_token" join-service.vue:684
          //error2 "The access token provided has expired" join-service.vue:685
          //error2 "Unauthorized" join-service.vue:686
          //error2 401
        console.log('error2 '+JSON.stringify(payload.response.data.error))
        console.log('error2 '+JSON.stringify(payload.response.data.error_description))
        console.log('error2 '+JSON.stringify(payload.response.statusText))
        console.log('error2 '+JSON.stringify(payload.response.status))
        */
        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>
.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>
