<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">
          <div class="row text-center">
            <div class="col-12">
              <b>View and Manage your builds</b>
            </div>
          </div>

<br>
          <div class="input-group input-group-sm sm-3">
              <div class="input-group-prepend">
                      <button
                              v-if="$socket.disconnected"
                              class="ti-unlink btn btn-outline-danger"
                              round
                              type="button"
                              title="You are disconnected from Swarmlab-hybrid"
                              disabled
                        >
                              </button>
                      <button
                              v-else
                              class="ti-link btn btn-outline-success"
                              round
                              type="button"
                              title="You are connected swarmlab-hybrid"
                              disabled
                      >
                              </button>
              </div>
              <div class="input-group-prepend">
<!--
                      <button
                              class="btn btn-outline-success"
                              round
                              type="button"
                              @click="onAction('start')"
                      >
                              Start</button>
-->
              </div>
              <div class="input-group-prepend">
                      <button
                              v-if="hybridshowdata.name"
                              class="btn btn-outline-success"
                              round
                              type="button"
                              @click="onAction('container-build')"
                      >
                              Build</button>
                      <button
                              v-if="hybridshowdata.name"
                              class="btn btn-outline-secondary ti-info"
                              round
                              type="button"
                              @click="onAction('container-build-info')"
                      >
                              </button>
                      <button
                              v-else
                              class="btn btn-outline-secondary"
                              round
                              type="button"
      												disabled
                      >
                              Connect</button>
                      <button
                              class="btn btn-outline-danger"
                              round
                              type="button"
                              @click="onAction('container-stop')"
                      >
                              Stop</button>
              </div>

              <div class="input-group-append">
              </div>

          </div>
      </b-container>
      <b-container fluid>
        <div class="row" >
          <div class="col-2 text-info" >
          ID
          </div>
          <div class="col-3 text-secondary" >
          {{ hybridshowdata.ID }}
          </div>
          <div class="col-2 text-info" >
          Image          
          </div>
          <div class="col-4 text-secondary" >
          {{ hybridshowdata.Image }}
          </div>
        </div> <!-- row -->
        <div class="row" >
          <div class="col-2 text-info" >
          Names
          </div>
          <div class="col-3 text-secondary" >
          {{ hybridshowdata.name }}
          </div>
          <div class="col-2 text-info" >
          RunningFor
          </div>
          <div class="col-4 text-secondary" >
          {{ hybridshowdata.RunningFor }}
          </div>
        </div> <!-- row -->
        <div class="row" >

          <div class="col-2 text-info" >
          Status
          </div>
          <div class="col-3 text-secondary" >
          {{ hybridshowdata.Status }}
          </div>

          <div class="col-2 text-info" >
          CreatedAt
          </div>
          <div class="col-4 text-secondary" >
          {{ hybridshowdata.CreatedAt }}
          </div>
        </div> <!-- row -->
        <div class="row" >

          <div class="col-2 text-info" >
                      <button
                              v-if="hybridshowdata.Networks&&addNetworkMenou==false"
                              class="btn btn-outline-info  btn-sm"
                              round
                              type="button"
                              @click="addNetwork(hybridshowdata,'on')"
                      >
                              Networks</button>
                      <button
                              v-if="hybridshowdata.Networks&&addNetworkMenou==true"
                              class="btn btn-outline-warning  btn-sm"
                              round
                              type="button"
                              @click="addNetwork(hybridshowdata,'off')"
                      >
                              Networks</button>
          </div>
          <div class="col-3 text-secondary" >
          {{ hybridshowdata.Networks }}
          </div>

          <div class="col-2 text-info" >
          Ports
          </div>
          <div class="col-4 text-secondary" >
          {{ hybridshowdata.Ports }}
          </div>
        </div> <!-- row -->
<!--
'{"ID":"{{ .ID }}", "Image": "{{ .Image }}", "Names":"{{ .Names }}", "Ports":"{{.Ports}}", 
"Networks":"{{.Networks}}", "Status":"{{.Status}}","RunningFor":"{{.RunningFor}}","CreatedAt":"{{.CreatedAt}}"}'
-->
      </b-container>

      <!-- Networks  -->

<div class="card border-success bg-light mb-3" style="max-width: 100%;"
	v-if="addNetworkMenou==true"
>
  <div class="card-header"></div>
  <div class="card-body text-info">
        <div class="row">
          <div class="col-6 text-info">
    				<h5 class="card-title">Select network</h5>
          </div>
          <div class="col-6 text-info">
						Connect a running container to multiple networks
          </div>
        </div>

        <div class="row">
          <div class="col-6 text-info">
						<b-form-select v-model="selectedNetworks" :options="localNetworkoptions" multiple :select-size="4"></b-form-select>
						<div class="mt-3">Selected: <strong>{{ selectedNetworks }}</strong></div>
          </div>
          <div class="col-6 text-info">
        			<img class="border-white img-thumbnail" src="@/assets/img/dockernetwork.png" alt="...">
          </div>
        </div>

        <div class="row">
          <div class="col-6 text-info">
                      <button
                              class="btn btn-outline-warning  btn-sm"
                              round
                              type="button"
                              @click="updateNetwork(hybridshowdata,'update')"
                      >
                              Update</button>
          </div>
        </div>


  </div>
</div>



  </card>
</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{
     addNetworkMenou:false,
     selectedNetworks:[],
     localNetworkoptions:[],
     localNetworkdefault:'',
     STATUS:{},
     CONFIG:{
         'status':'',
         'workerkey':'',
         'swarmlab_public_wgkey':'',
         'server_ip':'',
         'allowed_ips':'',
         'wg_port':'',
         'wg_ip':'',
         'swarm_ip':'',
         'privatekey':'',
         'publickey':'',
       'workerkey':'',
       'privatekey':'',
       'publickey':'',
       'server_ip':''
     },
     sshpid:0,
     buildpid:0,
     CONFIGallowed_ips:'',
     swarmlabname:'swarmlab-sec',
     swarmlabname_port:'',
     swarmlabname_size:3,
     swarmlabname_git:'',
        // run on 
     hybridshowdata:{},
     issocket:'close',
     setFilter: {},
     searchFor: {},
     resetFilter: {}
	 
		}
  },
  beforeMount () {
   this.socketopen();
   this.socketauthenticate()
        //console.log('send')
  },
	mounted() {
	//	this.$root.$on('SERVER_build_set_sshpid', (data) => {
  //    this.sshpid = data.pid
	//	})
		this.$root.$on('SERVER_build_set_buildpid', (data) => {
      this.buildpid = data.pid
		})
		this.$root.$on('BUILD_hybrid_show_info', (data) => {
			this.$nextTick(function () {
        this.hybridshowdata = data
     this.addNetworkMenou = false
     this.selectedNetworks = []
     this.localNetworkoptions = []
     this.localNetworkdefault = ''
        //console.log(JSON.stringify(this.hybridshowdata))
			})
		})
	},
	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 () {
		this.$root.$off('BUILD_hybrid_show_info')
		this.$root.$off('SERVER_build_set_buildpid')
		//this.$root.$off('SERVER_build_set_sshpid')
 },
  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 == 'container-logs'){
              //this.$socket.client.open();
              //this.$socket.client.emit('build-vmlist', 'test');
             //this.$root.$emit('SERVER_build_vmlist')
               console.log('logs---------- ' + JSON.stringify(this.hybridshowdata))	
          }else if(action == 'container-build-info'){
               var info = `
                <b-container fluid>
                  <div class="row text-center">
                    <div class="col-12">
                      <h4><b>Tips and caveats</b></h4>

                    <div class="list-group">
                      <div class="d-flex w-100 justify-content-between">
                        <h5 class="mb-1"><b>Install software</b></h5>
                      </div>
                       <p class="mb-1 list-group-item list-group-item-info">
                      <b>Vagrant, Packer</b> and  <b>VirtualBox</b> must be installed
                      </p>
                       <p class="mb-1 list-group-item list-group-item-info">
                         You can find installation instructions <a href="https://git.swarmlab.io:3000/swarmlab/swarmlab-build-install" target="new">here</a>
                      </p>


                    </div> <!-- list -->

                    </div> <!-- col -->
                  </div>   <!-- row -->
                </b-container fluid>
               `
               this.$swal({
                  type: 'info',
                  html: info,
                  showCloseButton: true,
                  showLoaderOnConfirm: false,
                  allowOutsideClick: false,
                  cancelButtonText: 'No, cancel!',
                  showCancelButton: false,
                  showLoaderOnConfirm: false,
                  reverseButtons: true,
                  focusCancel: false,
                  confirmButtonText: 'ok! '
                  })
          }else if(action == 'container-build'){
               var info = `
                <b-container fluid>
                  <div class="row text-center">
                    <div class="col-12">
                      <h4><b>Tips and caveats</b></h4>

                    <div class="list-group">
                      <div class="d-flex w-100 justify-content-between">
                        <h5 class="mb-1"><b>Disk space</b></h5>
                      </div>
                       <p class="mb-1 list-group-item list-group-item-info">
                      You need to run Builder on a machine with a <b>lot of free disk space</b> (sometimes 50 GB or more). <br> The installation media, VM(s) and box(es) take considerable amounts of space, at least temporarily.
                      </p>
                    </div> <!-- list -->

                    <div class="list-group">
                      <div class="d-flex w-100 justify-content-between">
                        <h5 class="mb-1"><b>Time</b></h5>
                      </div>
                       <p class="mb-1 list-group-item list-group-item-info">
                        Building a box <b>can easily take several hours</b>, most notably because installing OS updates is time-consuming.
                      </p>
                    </div> <!-- list -->
                    
                    <div class="list-group">
                      <div class="d-flex w-100 justify-content-between">
                        <h5 class="mb-1"><b>Incompatibilities</b></h5>
                      </div>
                      <p class="mb-1 list-group-item list-group-item-info">
                         Beware of version incompatibilities of hypervisors.
                       <small class="text-left list-group-item list-group-item-info">
                       For example a box built with VirtualBox 6.0 refusing to run on VirtualBox 5.<br>
                       </small>
                       If in doubt, deliberately use older hypervisor versions on the build machine.
                      </p>
                    </div> <!-- list -->

                    <div class="list-group">
                      <div class="d-flex w-100 justify-content-between">
                        <h5 class="mb-1"><b>Output</b></h5>
                      </div>
                      <p class="mb-1 list-group-item list-group-item-success">
                    The output of a successful build is a .box file.
                      </p>
                    </div> <!-- list -->
                    
                    <div class="list-group">
                      <div class="d-flex w-100 justify-content-between">
                        <h5 class="mb-1"><b>Install software</b></h5>
                      </div>
                      <p class="mb-1 list-group-item list-group-item-success">
                        With ansible you can install additional software into the box,
                      </p>
                    </div> <!-- list -->
                    

                    </div> <!-- col -->
                  </div>   <!-- row -->
                </b-container fluid>
               `
               this.$swal({
                  type: 'info',
                  html: info,
                  showCloseButton: true,
                  showLoaderOnConfirm: false,
                  allowOutsideClick: false,
                  cancelButtonText: 'No, cancel!',
                  showCancelButton: true,
                  showLoaderOnConfirm: false,
                  reverseButtons: true,
                  focusCancel: false,
                  confirmButtonText: 'Create the box! '
                  }).then((result)=> {
                    this.buildAndClose(result);
                  })

          }else if(action == 'container-stop'){
              var obj = {}
              obj.pid = this.buildpid
             console.log('PID '+ this.buildpid)
             this.$root.$emit('SERVER_build_kill',obj)
          }else if(action == 'stop'){
              this.$socket.client.emit('stop', this.swarmlabname);
          }
			},
      async buildAndClose(result){
          var obj = {}
          obj.name = this.hybridshowdata.name
          obj.dir = this.hybridshowdata.dir
          obj.config = this.hybridshowdata.config
          console.log('value result '+ JSON.stringify(result))
          console.log('value obj '+ JSON.stringify(obj))
          if (result.isConfirmed) {
            console.log('yes')       
            this.$root.$emit('SERVER_build_image',obj)
            // run on  mytable.vue
            //refresh table
            //this.$root.$emit('hybrid_stop_instance', value)
               var info = `
                <b-container fluid>
                  <div class="row text-center">
                    <div class="col-12">

                      <p class="mb-1 list-group-item list-group-item-success">
                    You can track the pending box creation from the embeded console or the graphical interface that will open.
                      </p>

                      <p class="mb-1 list-group-item list-group-item-info">
                    There will also be a spinny wheel above the console indicating work in proccess.
                      </p>

                      <p class="mb-1 list-group-item list-group-item-success">
                    Please note that closing the window(graphical) WILL NOT terminate the process.
                      </p>

                      <p class="mb-1 list-group-item list-group-item-info">
                    If you wish to forcefully stop you should use the STOP button.
                      </p>

                      <p class="mb-1 list-group-item list-group-item-success">
                    Note that the stop operation itself may take a little time.
                      </p>

                      <p class="mb-1 list-group-item list-group-item-light">
                    When the proccess is done you should see something like this:

                    <br>
                    ==> Builds finished. The artifacts of successful builds are:
                    <br>
                    --> virtualbox-iso: 'virtualbox' provider box: ../../builds/ubuntu-18.04.virtualbox.box
                    <br>
                    Build 'virtualbox-iso' finished after 1 hour 30  minutes 28 seconds
                      </p>


                    </div> <!-- col -->
                  </div>   <!-- row -->
                </b-container fluid>
               `
               this.$swal({
                  type: 'info',
                  html: info,
                  icon: 'info',
                  showCloseButton: true,
                  showLoaderOnConfirm: false,
                  allowOutsideClick: false,
                  cancelButtonText: 'No, cancel!',
                  showCancelButton: false,
                  showLoaderOnConfirm: false,
                  reverseButtons: true,
                  focusCancel: false,
                  confirmButtonText: 'ok! '
                  })
          }else  {
            console.log('no')       
          }
      },
  },


  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>
