<template>
  <card class="card-user" style="max-height:100%">
      <div class="author">
        <img class="avatar border-white" src="@/assets/img/code-128.png" alt="...">
      </div>
      <b-container fluid class="bv-example-row">
      	<div class=" col text-center">
						<v-wait for="myRunInstance1">
							<template slot="waiting">
								<div>
									<img src="@/assets/loading.gif" width="50" height="50" />
									Lab_Instance...
								</div>
							</template>
						</v-wait>


						<button type="button"
							round
							class="btn btn-outline-danger btn-sm"
							v-if="extenderror"
							@click="runextenderror()">
							Error: max depth exceeded</button>
						<button type="button"
							round
							class="btn btn-outline-warning btn-sm"
							v-if="tryConsole"
							@click="clear()">
							Clear</button>
						<button type="button"
							round
							class="btn btn-outline-info btn-sm"
							disabled
							>
							Console</button>
						<button type="button"
							round
							class="btn btn-outline-info btn-sm"
							v-if="cmOptions.keyMap == 'sublime'"
							@click="infoFilter">
							i</button>
                      
        </div>

        <div class="row">
          <div class="col-12">
                <div class="codemirror" >
                  <codemirror
                    ref="myCm"
                    :value="code"
                    :options="cmOptions"
                     @cursorActivity="onCmCursorActivity"
                    @ready="onCmReady"
                    @focus="onCmFocus"
                    @input="onCmCodeChange"
                  ></codemirror>
                </div>
             </div>
        </div>

</b-container>
	</card>
</template>
<script>
import {mapState, mapGetters, mapActions,dispatch} from 'vuex'
import Vue from 'vue'
import store from '@/store/index'                              


import { codemirror } from 'vue-codemirror'
import JSZip from 'jszip';
import FileSaver from 'file-saver';
import 'codemirror/lib/codemirror.css'
import 'codemirror/theme/mdn-like.css'
import card from '@/components/Card.vue'
  import 'codemirror/theme/idea.css'
import'codemirror/addon/selection/active-line.js'

import'codemirror/addon/hint/show-hint.js'
import'codemirror/addon/hint/show-hint.css'
import'codemirror/addon/hint/javascript-hint.js'
import'codemirror/addon/selection/active-line.js'
import'codemirror/addon/scroll/annotatescrollbar.js'
import'codemirror/addon/search/matchesonscrollbar.js'
import'codemirror/addon/search/searchcursor.js'
import'codemirror/addon/search/match-highlighter.js'

import'codemirror/mode/shell/shell.js'
import'codemirror/addon/edit/matchbrackets.js'
import'codemirror/addon/comment/comment.js'
import'codemirror/addon/dialog/dialog.js'
import'codemirror/addon/dialog/dialog.css'
import'codemirror/addon/search/searchcursor.js'
import'codemirror/addon/search/search.js'
import'codemirror/keymap/sublime.js'
import'codemirror/keymap/vim.js'

import'codemirror/addon/fold/foldgutter.css'
import'codemirror/addon/fold/brace-fold.js'
import'codemirror/addon/fold/comment-fold.js'
import'codemirror/addon/fold/foldcode.js'
import'codemirror/addon/fold/foldgutter.js'
import'codemirror/addon/fold/indent-fold.js'
import'codemirror/addon/fold/markdown-fold.js'
import'codemirror/addon/fold/xml-fold.js'
import 'codemirror/lib/codemirror';
import 'codemirror/addon/display/placeholder';

export default {
   components: {
      card,
			codemirror
   },
   data () {
    return {
      socketonline:false,
      extenderror:false,
      tryConsole:false,
      ssl:{},
      getinfo:'',
      token:'',
      swarmlabname:'',

      code: '',
      editchoice: '',
      optionsedit: [
        { text: 'code', value: 'code' },
        { text: 'text', value: 'text' }
      ],
     llodesc:[{
          llo_url                 : '',
          llo_name                : '',
          llo_author              : '',
          llo_intro               : ''
       }],
     llo:[{
          id                          :  0,
          rm                          :  false,
          data_info                   : 'Asciidoc \n',
          data_code                   : '#Your source code',
          data_service                : '',
          code_datafile               : 'url',
          code_name                   : '',
          code_exec                   : '',
          code_options                : '',
          code_mime                   : '',
          code_info                   : '',
          code_code                   : '',
          code_codeout                : '',
          code_codeoutput             : 'console',
          points                      : '',
          challenge_question          : '',
          code_challenge_question     : '',
          challenge_answer            : '',
          challenge_answer_hint       : '',
          code_challenge_answer_hint  : '',
          challenge_answer_source     : '',
          challenge_answer_code_out   : '',
          challenge_answer_code       : '',
          code_challenge_answer_code  : ''
       }],
		  searchLLO: [],
      searchLLOactive : false,
      ADOC_html_code:'',
      challenge:[],
      action:'',
      tryLLO:[],
      service:'os2',
      active:0,
      activecount:0,
      remove:'',
      activeField:'',
      bootstrap:false,
      firstbootstrap:0,
      htmlasciitmp:'',
      datafile: 'https://git.swarmlab.io:3000/labs/examples-mpi2/raw/branch/master/0_netstat/data',
      datadir: '0_netstat/data',
      LearningObject:'',
      showllo:true,
      showlloedit:true,
 		selected: 'sublime',
    options: [
      { text: 'vim', value: 'vim' },
      { text: 'sublime', value: 'sublime' }
    ],
    optionsmime: [
      { text: 'sh', value: 'bash' },
      { text: 'javascript', value: 'javascript' },
      { text: 'python', value: 'python' },
      { text: 'php', value: 'php' },
      { text: 'sql', value: 'sq;' },
      { text: 'xml', value: 'xml' },
      { text: 'c', value: 'c' }
    ],
        pValidate: false,
  cmOptions: {
    tabSize: 2,
    styleActiveLine: true,
    lineNumbers: true,
    lineSeparator:'\n',
    line: true,
    foldGutter: true,
    gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"],
    highlightSelectionMatches: { showToken: /\w/, annotateScrollbar: true },
    styleSelectedText: true,
    mode: 'shell',
    hintOptions:{
      completeSingle: false
    },
    keyMap: "sublime",
    //keyMap: "vim",
    matchBrackets: true,
    showCursorWhenSelecting: true,
    indentUnit:this.ADOC_html_code,
    lineWrapping: true,
    theme: 'idea',
    //theme: 'mdn-like',
    refresh:true,
    readOnly: true,
    autofocus: false,
    extraKeys: { "Ctrl": "autocomplete"  }
   },
    ADOC_html:[]
   }
  },
  methods: {

 socketconnect () {
    // send to runLLO
    this.$root.$emit('SERVER_socket_connect')
 },
 clear () {
      this.tryConsole = false
      this.code = ''
 },
 async getdata () {

              var field = this.getinfo
              var log = await store.dispatch("pipelineLLO/get_data",{
                code:field 
              })

 },

   async showactive(index) {
      this.topwindow(index)
		},
    onCmReady(cm) {
      cm.on('change', (cm, chg) => {
      }),
      cm.on('keypress', () => {
          cm.showHint({completeSingle:false})
      })
    },
    onCmCursorActivity(a, b, c) {
    },
    onCmFocus(cm) {
    },
    onCmCodeChange(newCode) {
      this.code = newCode
      //this.$root.$emit('socket_add',this.code)
    },
    handleChange() {
    },
    setKeymap () {
      this.cmOptions.keyMap = this.selected
    },
		infoFilter() {
				var title1='<h3>Playbook Images</h3>'
					var winfop='<table  class="table table-striped table-sm ">'+
 '<tr><td class="text-left">Shift-Tab</td> <td class="text-left">indentLess</td></tr>'+
 '<tr><td class="text-left">Alt-Q</td> <td class="text-left">wrapLines</td></tr>'+
 '<tr><td class="text-left">Ctrl-Up</td> <td class="text-left">scrollLineUp</td></tr>'+
 '<tr><td class="text-left">Ctrl-Down</td> <td class="text-left">scrollLineDown</td></tr>'+
 '<tr><td class="text-left">Ctrl-L</td> <td class="text-left">selectLine</td></tr>'+
 '<tr><td class="text-left">Esc</td> <td class="text-left">singleSelectionTop</td></tr>'+
 '<tr><td class="text-left">Ctrl-Enter</td> <td class="text-left">insertLineAfter</td></tr>'+
 '<tr><td class="text-left">Ctrl-D</td> <td class="text-left">selectNextOccurrence</td></tr>'+
 '<tr><td class="text-left">Shift-Ctrl-Space</td> <td class="text-left">selectScope</td></tr>'+
 '<tr><td class="text-left">Shift-Ctrl-M</td> <td class="text-left">selectBetweenBrackets</td></tr>'+
 '<tr><td class="text-left">Ctrl-M</td> <td class="text-left">goToBracket</td></tr>'+
 '<tr><td class="text-left">Ctrl-K Ctrl-Y</td> <td class="text-left">sublimeYank</td></tr>'+
 '<tr><td class="text-left">Ctrl-K Ctrl-C</td> <td class="text-left">showInCenter</td></tr>'+
 '<tr><td class="text-left">Ctrl-K Ctrl-G</td> <td class="text-left">clearBookmarks</td></tr>'+
 '<tr><td class="text-left">Ctrl-K Ctrl-Backspace</td> <td class="text-left">delLineLeft</td></tr>'+
 '<tr><td class="text-left">Ctrl-K Ctrl-0</td> <td class="text-left">unfoldAll</td></tr>'+
 '<tr><td class="text-left">Ctrl-K Ctrl-J</td> <td class="text-left">unfoldAll</td></tr>'+
 '<tr><td class="text-left">Ctrl-Alt-Up</td> <td class="text-left">addCursorToPrevLine</td></tr>'+
 '<tr><td class="text-left">Ctrl-Alt-Down</td> <td class="text-left">addCursorToNextLine</td></tr>'+
 '<tr><td class="text-left">Ctrl-F3</td> <td class="text-left">findUnder</td></tr>'+
 '<tr><td class="text-left">Shift-Ctrl-F3</td> <td class="text-left">findUnderPrevious</td></tr>'+
 '<tr><td class="text-left">Shift-Ctrl-[</td> <td class="text-left">fold</td></tr>'+
 '<tr><td class="text-left">Shift-Ctrl-]</td> <td class="text-left">unfold</td></tr>'+
 '<tr><td class="text-left">Ctrl-F</td> <td class="text-left">find</td></tr>'+
'</table>'
					
					var title1=''
					var winfo=''
				this.$swal({
					title: '<strong>Key bindings</strong>',
					type: 'info',
					html: winfop+title1+winfo,
					showCloseButton: true,
					showLoaderOnConfirm: false,
					allowOutsideClick: false
				})
		},
    async hotreload() {
              var field = this.getinfo
              var log = await store.dispatch("pipelineLLO/hotreload",{
                token:this.token,
                swarmlabname:this.swarmlabname 
              })
    },
	runextenderror	() {
 var html1 = ` <div style="overflow-x: auto;">
 <p>
 It's the total amount of layers; 
 </p>
 <p  class="text-left">
 <b>The current limit of 125 layers is due to the kernel's ARG_MAX</b>, which limits the number of arguments / length of arguments that can be passed when mounting the layers 
 
<br> <i> (this limit can be raised in kernels, but is not something that could be relied on as it would make those images non-interoperable on systems that don't have the custom configuration)</i>
 </p>
 <p  class="text-left">
 Note that not every step in a Dockerfile creates a new layer, <b>only (RUN) steps that modify the filesystem will introduce a new layer</b>.
 </p>

 <p  class="text-center">
 <h5> <b>Solution</b> </h5>
 </p>
 <p  class="text-left">
 Delete all local docker images related to your dockerfile using the following:
 <br>
 <br>
 <i><b>docker rmi -f $(docker images -a -q)</b></i>
 </p>

 <p  class="text-left">
 <h5> <b>Description</b> </h5>
 <br>
 Remove unused image <br>
 - all images not referenced by any container -
 </p>
 <p  class="text-left">
 <h5> <b>Filtering</b> </h5>
 <br>
 <i><b>docker rmi -f $(docker images -a | grep "IMAGE_NAME" | awk '{ print $3 }')</b></i>
 </p>

</div>`

				this.$swal({
					title: '<strong>Info</strong>',
					type: 'info',
					html: html1,
					showCloseButton: true,
					showLoaderOnConfirm: false,
					allowOutsideClick: false
				})
		}

  },
  computed: {
    codemirror() {
      return this.$refs.myCm.codemirror
   }

	},
	mounted() {
    // from runLLO
		this.$root.$on('SERVER_socket_status', (v) => {
			this.$nextTick(function () {
        if(v == 'off'){
          this.socketonline = false
        }else if(v == 'on'){
          this.socketonline = true
        }
			})
		})
    // from runLLO
		this.$root.$on('hybrid_log_in', (log) => {
               //this.code += JSON.stringify(log)
               //this.code += log.data
               //this.code += "\n"
               //console.log(" form socket log "+JSON.stringify(this.code))
        var doc = this.$refs.myCm.codemirror.getDoc();
        var cursor = doc.getCursor(); // gets the line number in the cursor position
        //console.log(" form socket log "+JSON.stringify(cursor))
        var line = doc.getLine(cursor.line); // get the line contents
        var pos = { // create a new object to avoid mutation of the original selection
            line: cursor.line,
            ch: line.length - 1 // set the character position to the end of the line
          }
        doc.replaceRange(log.data, pos); // adds a new line
        doc.replaceRange("\n", pos); // adds a new line
        this.$refs.myCm.codemirror.setCursor(this.$refs.myCm.codemirror.lineCount(), 0);
        //var extenderror = /hello/;
        var extenderror = new RegExp('max depth exceeded'); 
        if(extenderror.test(log.data)){
            this.extenderror = true
            //console.log('find');
        }else{
            console.log('not find');
        }

        this.tryConsole=true
		})
    // from mytable.vue and socket
		this.$root.$on('SERVER_hybrid_table_start', (v) => {
			this.$nextTick(function () {
        this.$wait.start('myRunInstance1');
			})
		})
    // from mytable.vue and socket
		this.$root.$on('SERVER_hybrid_table_stop', (v) => {
			this.$nextTick(function () {
        this.$wait.end('myRunInstance1');
			})
		})

	},
  beforeDestroy () {
		this.$root.$off('SERVER_socket_status')
		this.$root.$off('hybrid_log_in')
		this.$root.$off('SERVER_hybrid_table_start')
		this.$root.$off('SERVER_hybrid_table_stop')
 },

		created () {
      this.token = new  URL(location.href).searchParams.get('token');
      this.swarmlabname = new  URL(location.href).searchParams.get('pipelinename');
		}
};
</script>

<style>
.CodeMirror {
    font-family: monospace;
    height: 550px;
}

</style>
