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

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

      <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">
              <card class="card-user" style="max-height:100%" >

 <span
    class="notification"
    v-if="$socket.disconnected"
  >
    You are disconnected
  </span>
 <span
    class="notification"
    v-else
  >
    You are connected
  </span>


    <div class="input-group input-group-sm sm-3">
                        <div class="input-group-prepend">
                                <button
                                        class="btn btn-outline-primary"
                                        round
                                        type="button"
                                        @click="onAction('start')"
        >
                                        Start</button>
                        </div>
                        <div class="input-group-prepend">
                                <button
                                        class="btn btn-outline-primary"
                                        round
                                        type="button"
                                        @click="onAction('stop')"
        >
                                        Stop</button>
                        </div>

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













              </card>
          </b-container>
      </card>

  </div>
</template>
<script>
import store from '@/store/index'
import {mapState, mapGetters, mapActions,dispatch} from 'vuex'
import Vue from 'vue'
import card from '@/components/Card.vue'
import {ApiConfig} from "@/config/index";
import { extend } from 'vee-validate';
import { required, alpha_num } from 'vee-validate/dist/rules';

// No message specified.
extend('alpha_num', alpha_num);

// Override the default message.
extend('required', {
  ...required,
  message: 'This field is required'
});

export default {
  components: {
      card
	},
  props: {
  },
  data() {
   return{
     issocket:'close',
     setFilter: {},
     searchFor: {},
     resetFilter: {}
	 
		}
  },
  beforeMount () {
   this.socketopen();
   this.socketauthenticate()
        console.log('send')
  },
	mounted() {
	},
	created() {
    var url_string = window.location.href
    var url = new URL(url_string);
    this.token = url.searchParams.get("token");
    console.log("token "+ this.token);
      var log = store.dispatch("pipelineLLO/settoken",{
        token:this.token
      })
     this.socketopen();

	},
    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 onAction(action){
        if(action == 'start'){
      /*
               var log = await store.dispatch("pipelineLLO/swarmlabstartget",{
                          token:this.token,
                          action:'add'
                        })
      */
              var obj = {}
              obj.action = 'up'
              obj.token = this.token
              //this.$socket.client.emit('action', obj);
              //this.$socket.client.emit('actionstart', obj);
              this.$socket.client.open();
              this.$socket.client.emit('start', 'test');
               //console.log('start ' + JSON.stringify(log))	
               console.log('startobj ' + JSON.stringify(obj))	
              //console.log(this.$socket.client.connect())
          }else if(action == 'stop'){
              this.$socket.client.emit('stop', 'test');
          }
			},
   async socketopen () {
        this.$socket.client.open();
        this.$socket.client.connect();
   },
   async socketauthenticate () {
        this.$socket.client.emit('authenticate', this.token);
   },
   async socketreconnect () {
          var log = await this.socketopen() 
          this.socketauthenticate()
   },
   async socketclose () {
        this.$socket.client.close();
   }

  },
 /**
 *
 * == Socket events
 * 
 * [source,javascript]
 * ----   
 *   this.$socket.client.emit('authenticate', 'logintoken');
 * ----   
 *
 */
     sockets: {
      connect() {
        //this.$socket.client.emit('authenticate', this.token);
        console.log('socket connected '+ 'socketdatasend' )
        this.issocket = 'open'
      },
 /**
 *
 * === onError
 *
 */
      error(error) {
        console.log("socket error "+JSON.stringify(error))
        this.issocket = 'close'
      },
 /**
 *
 * === connect_error
 * 
 */
      connect_error(error) {
        console.log("socket connect_error "+JSON.stringify(error))
        this.issocket = 'close'
          this.socketopen() 
          this.socketreconnect() 
      },
 /**
 *
 * === connect_error
 *
 */
      disconnect(reason) {
        console.log("socket disconnect "+JSON.stringify(reason))
        this.issocket = 'close'
          this.socketreconnect() 
      },
 /**
 * 
 * === Socket connect_timeout
 * 
 */
      connect_timeout(reason) {
        console.log("socket timeout "+JSON.stringify(reason))
        this.issocket = 'close'
          this.socketreconnect() 
      },
 /**
 * 
 * === Socket reconnect
 * 
 */
      reconnect(attemptNumber) {
        console.log("socket reconnect attemptNumber "+JSON.stringify(attemptNumber))
          this.socketreconnect() 
      },
 /**
 * 
 * === connect_attempt
 * 
 */
      reconnect_attempt(attemptNumber) {
        console.log("socket reconnect_attempt "+JSON.stringify(attemptNumber))
          this.socketreconnect() 
      },
 /**
 *
 * === Socket reconnecting
 *
 */
      reconnecting(attemptNumber) {
        console.log("socket reconnecting "+JSON.stringify(attemptNumber))
          this.socketreconnect() 
      },
 /**
 *
 * === reconnect_error
 *
 */
      reconnect_error(error) {
        console.log("socket reconnect_error "+JSON.stringify(error))
        this.issocket = 'close'
          this.socketreconnect() 
      },
 /**
 *
 * === unauthorized
 *
 */
      unauthorized(val) {
        console.log("socket unauthorized "+JSON.stringify(val))
        this.issocket = 'close'
      },
 /**
 *
 * === connected 
 *
 */
      socket_id_emit(val) {
        console.log("socket id from server "+JSON.stringify(val))
        this.issocket = 'open'
      },
 /**
 *
 * === Socket onMessage
 *
 */
 /*
      async adhocEmit(val) {
        console.log("socket from server "+JSON.stringify(val))
        this.issocket = 'open'
            this.$wait.start('myRunInstance1');
                // render begin
                this.tryLLO = 'on'
                if(this.firstbootstrap === 0 ){
                    await this.bootsrapllo();
                    this.firstbootstrap = 1
                }
                var output = log.data.out
                var mydinfunction = `
                  <div class="row">
                      <b-col  class="" cols="12" sm="12"  md="12" >
                            ${output}
                       </b-col>
                  </div>`

                  try {
                     let divascii = document.createElement('div');
                     divascii.setAttribute("class", "container-fluid w-100 p-3 llotry")
                     divascii.innerHTML = mydinfunction
                     this.addtask(divascii);
                  }catch (ex) {
                      console.log(" logi error1 "+JSON.stringify(ex))
                      return
                  }
            this.$wait.end('myRunInstance1');
      },
      */
    async logdata(val) {
        console.log(" socket from logdata "+JSON.stringify(val))
        // -------------------------------------
        //  Save store
        // -------------------------------------
        var log = store.dispatch("pipelineLLO/addlog",{
          log:val
        })

        var ltmp = store.getters['pipelineLLO/getlog'];
          this.log_path = [...new Set(ltmp.map(item => item.tailed_path))];
          var loglenght = ''
          for (let item of this.log_path) {
             //console.log('l1find '+ JSON.stringify(item))
             loglenght = ltmp.filter(item1 => item1.tailed_path === item).length;
             Vue.set(this.log_path_lenght, item, loglenght);
             if(loglenght > this.loglenghttotal){
                  // -------------------------------------
                  //  Save store
                  // -------------------------------------
                  var ltotal1 = store.dispatch("pipelineLLO/taillog",{
                    path:item
                  })
             }
          }
          
      },
    async message(val) {
        console.log(" socket message "+JSON.stringify(val))
      },
    async message_out(val) {
        console.log(" socket out "+JSON.stringify(val))
        this.$root.$emit('hybrid_log_in',val)
      },
    async message_err(val) {
        console.log(" socket err "+JSON.stringify(val))
        this.$root.$emit('hybrid_log_in',val)
      },
    async message_close(val) {
        console.log(" socket close "+JSON.stringify(val))
        this.$root.$emit('hybrid_log_in',val)
      }
  },


  actions: {

	}

};
</script>

<style lang="scss">



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