<template>
  <card class="card-user" style="max-height:100%"
		v-show="menou"
	>
      <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="row"
   v-if="menouselect"
 >
    <div class="col-sm-12 sm-12">
    	<b-form-select v-model="selected" :options="options" size="sm" class="mt-3"
			    @change="setservice">
      ></b-form-select>
    </div>
  </div>

 <div class="row">
    <div class="col-sm-12 sm-12">
      <div class="input-group">
        <div class="input-group-prepend">
          <span class="input-group-text" name="validationTooltipUsernamePrepend1">Base Service Name</span>
        </div>
        <input 	
					type="text" 
					class="form-control text-success" 
				  v-model="form_baseservice"
				  disabled
					aria-describedby="validationTooltipUsernamePrepend1" 
				>
      </div>
    </div>
  </div>

   <ValidationProvider
			ref="hybrid_stackname"
			name="myServicename"
			rules="required|alpha_num_name"
			v-slot="{ errors, ariaMsg, ariaInput,   valid, invalid }"
		>
 <div class="row">
			<div class="col-sm-12 sm-12">
       <div class="input-group input-group-sm sm-3">
        <div class="input-group-prepend">
          <span class="input-group-text" >Service &nbsp; Name</span>
        </div>
				<input 
					type="text" 
					class="form-control" 
					v-bind:class="{'is-valid': isDeployValid.stackname == 1, 'is-invalid': isDeployValid.stackname == 2}"
          aria-label="Small" aria-describedby="inputGroup-sizing-sm"
					v-model="form_myservicename"
					v-on:keyup="isValid('stackname')"
					v-on:blur="isValid('stackname')"
					v-on:input="isValid('stackname')"
					v-on:change="isValid('stackname')"
					v-on:focus="isValid('stackname')"

          data-vv-as='"nyServicename"'
          data-vv-value-path="form_myservicename"
          data-vv-name="form_myservicename"

				>
			 </div>
			</div>
  </div>
	  <span class="hybrid-field-error">{{ errors[0] }}</span>
	 </ValidationProvider>

   <ValidationProvider
			ref="hybrid_stackversion"
			name="myVersion"
			rules="required|alpha_num_name"
			v-slot="{ errors, ariaMsg, ariaInput,   valid, invalid }"
		>
				 <div class="row">
						<div class="col-sm-12 sm-12">
						 <div class="input-group input-group-sm sm-3">
        <div class="input-group-prepend">
          <span class="input-group-text" >Service Version</span>
        </div>
							<input 
								type="text" 
								class="form-control" 
									aria-label="Small" aria-describedby="inputGroup-sizing-sm"
									v-bind:class="{'is-valid': isDeployValid.stackversion == 1, 'is-invalid': isDeployValid.stackversion == 2}"
								name="myVersion"  
								v-model="form_version"
								v-on:keyup="isValid('stackversion')"
                v-on:blur="isValid('stackversion')"
                v-on:input="isValid('stackversion')"
                v-on:change="isValid('stackversion')"
                v-on:focus="isValid('stackversion')"
							>
						</div>
					 </div>
					</div>
	  <span class="hybrid-field-error">{{ errors[0] }}</span>
	 </ValidationProvider>

 <div class="row">
    <div class="col-sm-12 sm-12">
      <div class="input-group">
        <div class="input-group-prepend">
          <span class="input-group-text" name="validationTooltipUsernamePrepend">Git-repo</span>
        </div>
        <input 	
					type="text" 
					class="form-control" 
				  v-model="form_gitrepo"
					name="validationTooltipUsername" 
					aria-describedby="validationTooltipUsernamePrepend" 
				>
      </div>
    </div>
  </div>


    <div class="row"
      <b-col  class="text-center" cols="12" sm="12"  md="12">
        <div class="form-group">
          <label for="customreadme" class="text-dark"> <b>README </b>  <br>
          </label>
          <textarea class="form-control" name="customreadme" rows="8"
				      v-model="form_readme"
          >
          {{ form_readme }}
          </textarea>
        </div>
      </b-col>
    </div>


    <div class="row"
      <b-col  class="text-center" cols="12" sm="12"  md="12">
        <div class="form-group">
          <label for="custompackages" class="text-dark"><b>Add Extrapackages</b>  <br>
          <span class="text-success">
          {{ customostext }}
          </span >
          </label>
          <textarea class="form-control" name="custompackages" rows="8"
          placeholder="e.g. apt-get update && apt-get -y install or apk update && apk add --no-cache  "
				      v-model="form_os"
          >
          {{ form_os }} 
          </textarea>
        </div>
      </b-col>
    </div>

    <div class="row"
      <b-col  class="text-center" cols="12" sm="12"  md="12">
        <div class="form-group">
          <label for="customshell" class="text-dark"><b>Custom sh script</b> <br>
          <span class="text-success">
          {{ customshtext }}
          </span >
          </label>
          <textarea class="form-control" name="customshell" rows="8"
          placeholder="#!/bin/bash  "
				      v-model="form_sh"
          >
          {{ form_sh }}
          </textarea>
        </div>
      </b-col>
    </div>

 <div class="row">
    <div class="col-sm-3 sm-3">
      <div class="input-group">
        <div class="input-group-prepend">
          <span class="input-group-text" name="validationTooltipUsernamePrepend">Port</span>
        </div>
        <input 	
					type="text" 
					class="form-control" 
				  v-model="form_port1"
					aria-describedby="validationTooltipUsernamePrepend" 
				>
      </div>
    </div>

    <div class="col-sm-4 sm-4">
      <div class="input-group">
        <div class="input-group-prepend">
          <span class="input-group-text" name="validationTooltipUsernamePrepend">URI</span>
        </div>
        <input 	
					type="text" 
					class="form-control" 
				  v-model="form_url1"
          placeholder="http/https"
					aria-describedby="validationTooltipUsernamePrepend" 
				>
      </div>
    </div>

    <div class="col-sm-5 sm-5">
      <div class="input-group">
        <div class="input-group-prepend">
          <span class="input-group-text" name="validationTooltipUsernamePrepend1a">Name</span>
        </div>
        <input 	
					type="text" 
					class="form-control" 
				  v-model="form_name1"
					aria-describedby="validationTooltipUsernamePrepend1a" 
				>
      </div>
    </div>

  </div>

 <div class="row">
    <div class="col-sm-3 sm-3">
      <div class="input-group">
        <div class="input-group-prepend">
          <span class="input-group-text" name="validationTooltipUsernamePrepend2">Port</span>
        </div>
        <input 	
					type="text" 
					class="form-control" 
				  v-model="form_port2"
					aria-describedby="validationTooltipUsernamePrepend2" 
				>
      </div>
    </div>


    <div class="col-sm-4 sm-4">
      <div class="input-group">
        <div class="input-group-prepend">
          <span class="input-group-text" name="validationTooltipUsernamePrepend">URI</span>
        </div>
        <input 	
					type="text" 
					class="form-control" 
				  v-model="form_url2"
          placeholder="http/https"
					aria-describedby="validationTooltipUsernamePrepend" 
				>
      </div>
    </div>

    <div class="col-sm-5 sm-5">
      <div class="input-group">
        <div class="input-group-prepend">
          <span class="input-group-text" name="validationTooltipUsernamePrepend2a">Name</span>
        </div>
        <input 	
					type="text" 
					class="form-control" 
				  v-model="form_name2"
					aria-describedby="validationTooltipUsernamePrepend2a" 
				>
      </div>
    </div>

  </div>

 <div class="row">
    <div class="col-sm-3 sm-3">
      <div class="input-group">
        <div class="input-group-prepend">
          <span class="input-group-text" name="validationTooltipUsernamePrepend3">Port</span>
        </div>
        <input 	
					type="text" 
					class="form-control" 
				  v-model="form_port3"
					aria-describedby="validationTooltipUsernamePrepend2" 
				>
      </div>
    </div>

    <div class="col-sm-4 sm-4">
      <div class="input-group">
        <div class="input-group-prepend">
          <span class="input-group-text" name="validationTooltipUsernamePrepend">URI</span>
        </div>
        <input 	
					type="text" 
					class="form-control" 
				  v-model="form_url3"
          placeholder="http/https"
					aria-describedby="validationTooltipUsernamePrepend" 
				>
      </div>
    </div>

    <div class="col-sm-5 sm-5">
      <div class="input-group">
        <div class="input-group-prepend">
          <span class="input-group-text" name="validationTooltipUsernamePrepend3a">Name</span>
        </div>
        <input 	
					type="text" 
					class="form-control" 
				  v-model="form_name3"
					aria-describedby="validationTooltipUsernamePrepend3a" 
				>
      </div>
    </div>

  </div>


    <div class="row"
      <b-col  class="text-center" cols="12" sm="12"  md="12">
        <div class="form-group">
          <label for="rclocal" class="text-dark"><b>rc.local</b> <br>
          <span class="text-success">
          {{ customshtext }}
          </span >
          </label>
          <textarea class="form-control" name="rclocal" rows="8"
				      v-model="form_rclocal"
          >
          {{ form_rclocal }}
          </textarea>
        </div>
      </b-col>
    </div>

 <div class="row">
    <div class="col-sm-12 sm-12 float-right">
  			<button 
          class="btn btn-outline-info  btn-sm float-right"
					type="submit"
					@click="save"
				>Save Microservice</button>
  			<button 
          class="btn btn-outline-warning  btn-sm float-right"
					type="submit"
					@click="cancel"
				>Cancel</button>
    </div>
  </div>


      </b-container>
  </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 { ValidationObserver, ValidationProvider, extend } from 'vee-validate';
//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'
});


extend('alpha_num_name', value => {
 var regex = new RegExp(/^[A-Za-z0-9]+$/, 'i');
  if(regex.test(value)){
    return true;
  }
  return 'The {_field_} field may contain alphabetic characters and numbers'
});




export default {
  components: {
      ValidationProvider,
      card
	},
  props: {
  },
  data() {
   return{
    customostext: '',
    customshtext: '',
    menou: false,
     custom: {
			'os':'',
			'sh':'',
     },
     customserviceall: [],
			'form_baseservice':'',
			'form_myservicename':'',
			'form_os':'',
			'form_sh':'',
      'form_readme': '',
			'form_version':'',
			'form_rclocal':'',
      'form_url1':'',
      'form_url2':'',
      'form_url3':'',
			'form_port1':'',
			'form_name1':'',
			'form_port2':'',
			'form_name2':'',
			'form_port3':'',
			'form_name3':'',
			'form_gitrepo':'',
     customservice: {
			'myservicename':'',
			'os':'',
			'sh':'',
      'readme': '',
			'microservice':'',
			'version':'',
			'rclocal':'',
      'url1':'',
      'url2':'',
      'url3':'',
			'port1':'',
			'name1':'',
			'port2':'',
			'name2':'',
			'port3':'',
			'name3':'',
			'gitrepo':''
     },
     addNetworkMenou:false,
     issocket:'close',
    isDeployValid:{
      "stackname":3,
      "stackversion":3
      },
    isDeployError:{
      },
  			selected: 1,
        menouselect: false,
        options: [
         {"value":99999,"text":"Please select an option"}
        ]
		}
  },
  beforeMount () {
  },
	mounted() {
		this.$root.$on('hybrid_build_micro_service_menou', ()  => {
			this.menou = false
      //console.log('false')
    })
		this.$root.$on('hybrid_build_micro_service', (service) => {
      console.log(service);
      this.setserviceform2null()
			this.menou = true
			this.myservicename = {}
			this.customserviceall = []
			this.options = []
			this.customservice = {}
      this.menouselect = false
			this.customservice.microservice = service.data.swarmlabname	
			this.form_baseservice = service.data.swarmlabname	

      if( service.log.hasOwnProperty('data')){
      	if( service.log.data.hasOwnProperty('data')){
           if(service.log.data.data){
              //const cc = service.log.data.data.filter(item => item.service === '0').length; 
              var cc = Object.keys(service.log.data.data).length;
              if(cc > 0){
                if(cc > 1){
                	this.menouselect = true
								}
              	cc--
							}
                //console.log(cc)
							this.customservice.myservicename	= service.log.data.data[cc].service
							this.customservice.baseservice		=	service.log.data.data[cc].baseservice
							this.customservice.sh							= service.log.data.data[cc].sh
							this.customservice.os							= service.log.data.data[cc].packages
							this.customservice.readme					= service.log.data.data[cc].readme
							this.customservice.gitrepo				= service.log.data.data[cc].gitrepo
							this.customservice.version				= service.log.data.data[cc].serviceversion
							this.customservice.rclocal				= service.log.data.data[cc].rclocal

							this.customservice.url1    			  = service.log.data.data[cc].url1
							this.customservice.url2    			  = service.log.data.data[cc].url2
							this.customservice.url3    			  = service.log.data.data[cc].url3
							this.customservice.port1    			= service.log.data.data[cc].port1
							this.customservice.name1    			= service.log.data.data[cc].name1
							this.customservice.port2    			= service.log.data.data[cc].port2
							this.customservice.name2    			= service.log.data.data[cc].name2
							this.customservice.port3    			= service.log.data.data[cc].port3
							this.customservice.name3    			= service.log.data.data[cc].name3
              this.setserviceform(this.customservice) 

							for (let i = 0; i <= cc; i++) {
								  let option = { 
									  value: i,
									  text: service.log.data.data[i].service
                  }
                  Vue.set(this.options, i, option)
                  this.selected = i
							}
							this.customserviceall				= service.log.data.data
                console.log('customall2 '+ JSON.stringify(this.customservice.myservicename))
                console.log('customall1 '+ JSON.stringify(service.log.data.data[cc]))
                console.log('customall '+ JSON.stringify(this.customserviceall))
						}
      	}
      }
         this.selected++
         var vtmp1 = {"value":this.selected,"text":"Please select an option"}
         Vue.set(this.options, this.selected, vtmp1)
                console.log('options '+ JSON.stringify(this.options))

		})

		this.$root.$on('hybrid_build_micro_myservice', (service) => {
			this.menou = true
			this.myservicename = {}
			this.customserviceall = []
			this.customservice = {}
      this.menouselect = false
			this.customservice.microservice = service.data.swarmlabname	

      if( service.log.hasOwnProperty('data')){
      	if( service.log.data.hasOwnProperty('data')){
           if(service.log.data.data){
							this.customservice.myservicename	= service.log.data.data.service
							this.customservice.baseservice		=	service.log.data.data.baseservice
							this.customservice.sh							= service.log.data.data.sh
							this.customservice.os							= service.log.data.data.packages
							this.customservice.readme					= service.log.data.data.readme
							this.customservice.gitrepo				= service.log.data.data.gitrepo
							this.customservice.version				= service.log.data.data.serviceversion
							this.customservice.rclocal				= service.log.data.data.rclocal

							this.customservice.url1    			  = service.log.data.data.url1
							this.customservice.url2    			  = service.log.data.data.url2
							this.customservice.url3    			  = service.log.data.data.url3
							this.customservice.port1    			= service.log.data.data.port1
							this.customservice.name1    			= service.log.data.data.name1
							this.customservice.port2    			= service.log.data.data.port2
							this.customservice.name2    			= service.log.data.data.name2
							this.customservice.port3    			= service.log.data.data.port3
							this.customservice.name3    			= service.log.data.data.name3
              this.setserviceform(this.customservice) 
						}
      	}
      }

		})
	},
	created() {
    var url_string = window.location.href
    var url = new URL(url_string);
    this.token = url.searchParams.get("token");
      var log = store.dispatch("pipelineLLO/settoken",{
        token:this.token
      })

	},
    beforeDestroy () {
			this.$root.$off('hybrid_build_micro_service')
			this.$root.$off('hybrid_build_micro_myservice')
			this.$root.$off('hybrid_build_micro_service_menou')
 },
  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 save() {
     (async () => {
          var isAllValid = true
          for (const [key, value] of Object.entries(this.isDeployValid)) {
            //console.log(`${key}: ${value}`);
            if(value != 1){
              isAllValid = false
            }
          }
 				if(isAllValid){
						
              var log = await store.dispatch("pipelineLLO/addmycustomservice",{
                token:this.token,
								service:        this.form_myservicename,
								readme:         this.form_readme,
								baseservice:    this.form_baseservice,
								sh:             this.form_sh,
								packages:       this.form_os,
								gitrepo:        this.form_gitrepo,
								serviceversion: this.form_version,
								rclocal:        this.form_rclocal,
								url1:           this.form_url1,
								url2:           this.form_url2,
								url3:           this.form_url3,
								port1:          this.form_port1,
								name1:          this.form_name1,
								port2:          this.form_port2,
								name2:          this.form_name2,
								port3:          this.form_port3,
								name3:          this.form_name3
              })
            //  this.$root.$emit('hybrid_refresh_bootstrap_view')
            //  this.$root.$emit('hybrid_refresh_bootstrap_view')
						
    	  			console.log(this.customservice);
    	  			//console.log(log);
              if(log.data.action == 'ok'){
                  var info = "Your upload was successful!"
                  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!'
                  })
              this.$root.$emit('hybrid_build_micro_service_menou_refreshtable')

              }else{
                  var info = "Service upload error "
                  this.$swal({
                    type: 'Info',
                    title: 'Info!',
                    icon:'error',
                    html: info,
                    showCloseButton: true,
                    showLoaderOnConfirm: false,
                    allowOutsideClick: false,
                    cancelButtonText: 'No, cancel!',
                    showCancelButton: false,
                    showLoaderOnConfirm: false,
                    reverseButtons: true,
                    focusCancel: true,
                    confirmButtonText: 'Ok!'
                  })
              }
          }else{
              var info = "Missing required fields"
              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!'
              })

         }
      })();

		},
    cancel() {
    	//console.log('cancel');
			this.menou = false
		},
    setserviceform(data) {
      this.form_myservicename	  = data.myservicename
      this.form_baseservice			=	data.baseservice
      this.form_sh							= data.sh
      this.form_os							= data.os
      this.form_readme					= data.readme
      this.form_gitrepo				  = data.gitrepo
      this.form_version				  = data.version
      this.form_rclocal				  = data.rclocal

      this.form_url1    			  = data.url1
      this.form_url2    			  = data.url2
      this.form_url3    			  = data.url3
      this.form_port1    			  = data.port1
      this.form_name1    			  = data.name1
      this.form_port2    			  = data.port2
      this.form_name2    			  = data.name2
      this.form_port3    			  = data.port3
      this.form_name3    			  = data.name3
      //console.log(data)
      //console.log(data.myservicename)
      //console.log(this.form_myservicename)
		},
    setserviceform2null() {
      this.form_myservicename	  = '' 
      this.form_baseservice			= ''	
      this.form_sh							= '' 
      this.form_os							= '' 
      this.form_readme					= '' 
      this.form_gitrepo				  = '' 
      this.form_version				  = '' 
      this.form_rclocal				  = '' 

      this.form_url1    			  = '' 
      this.form_url2    			  = '' 
      this.form_url3    			  = '' 
      this.form_port1    			  = '' 
      this.form_name1    			  = '' 
      this.form_port2    			  = '' 
      this.form_name2    			  = '' 
      this.form_port3    			  = '' 
      this.form_name3    			  = '' 
      console.log('refresh')
      //console.log(data.myservicename)
      //console.log(this.form_myservicename)
		},
    setservice() {
    	//console.log(this.selected);
    	var cc = this.selected
      console.log('sel '+ JSON.stringify(this.customserviceall[cc]))

      this.customservice.myservicename	= this.customserviceall[cc].service

      this.customservice.baseservice					=	this.customserviceall[cc].baseservice
      this.customservice.sh							= this.customserviceall[cc].sh
      this.customservice.os							= this.customserviceall[cc].packages
      this.customservice.readme					= this.customserviceall[cc].readme
      this.customservice.gitrepo				= this.customserviceall[cc].gitrepo
      this.customservice.version				= this.customserviceall[cc].serviceversion
      this.customservice.rclocal				= this.customserviceall[cc].rclocal

      this.customservice.url1    			  = this.customserviceall[cc].url1
      this.customservice.url2    			  = this.customserviceall[cc].url2
      this.customservice.url3    			  = this.customserviceall[cc].url3
      this.customservice.port1    			= this.customserviceall[cc].port1
      this.customservice.name1    			= this.customserviceall[cc].name1
      this.customservice.port2    			= this.customserviceall[cc].port2
      this.customservice.name2    			= this.customserviceall[cc].name2
      this.customservice.port3    			= this.customserviceall[cc].port3
      this.customservice.name3    			= this.customserviceall[cc].name3

      //this.customservice.readme	= 'xxxxxxxxxxxxxxxxxx'
      //Vue.set(this.customservice, 'readme', 'xxxxxxxxxxxxxxxxxxxxxxxxx' )
      //console.log('sel1 '+ JSON.stringify(this.customservice))
      this.setserviceform(this.customservice) 
		},
   async isValid(f){

     if(f == 'stackname'){
        var field = await this.$refs.hybrid_stackname.validate();
        if(field.valid == true){
          this.isDeployValid.stackname = 1
        }else{
          this.isDeployValid.stackname = 2
        }
     }
     else if(f == 'stackversion'){
        var field = await this.$refs.hybrid_stackversion.validate();
        if(field.valid == true){
          this.isDeployValid.stackversion = 1
        }else{
          this.isDeployValid.stackversion = 2
        }
     }
 }





  },

  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>
