<template>
    <div class="console" id="terminal"></div>
</template>

<script>
import SockJS from  'sockjs-client';
// import Terminal from './term';
import { Terminal } from 'xterm'
import * as fit from 'xterm/lib/addons/fit/fit'
import * as attach from 'xterm/lib/addons/attach/attach'
export default {
    name: 'term',
    props: {
        res: (Object,String)
    },
    data () {
        return {
            term: null,
            terminalSocket: null
        }
    },
    methods: {
        runRealTerminal () {
            console.log('webSocket is finished')
        },
        errorRealTerminal () {
            console.log('error')
        },
        closeRealTerminal () {
            console.log('close')
        }
    },
    beforeMount (){
        Terminal.applyAddon(fit)
        Terminal.applyAddon(attach)
    },
    mounted () {
        let that = this;
        let terminalContainer = document.getElementById('terminal')
        that.term = new Terminal({
            fontSize: 14,
            fontFamily: 'Consolas, "Courier New", monospace',
            bellStyle: 'sound',
            cursorBlink: true,
        })
        that.term.open(terminalContainer)
        that.term.focus();
        that.term.fit();
    
        // setTimeout(() => {
        //     that.term.fit();
        // }, 100);
        fetch('/devopsApi/createPodAttachSession/5d134c4f7cb0322f6049c785/devops-api-1-0-d5dc659cc-jd7d5').then(res =>{
            res.json().then(result => {
            that.terminalSocket = new SockJS('/devopsApi/api/sockjs?' + result.sessionId);
            that.terminalSocket.onopen = function() {
                const startData = {Op: 'bind', SessionID: result.sessionId};
                that.terminalSocket.send(JSON.stringify(startData));
            };
            that.terminalSocket.onmessage = function(e) {
                const frame = JSON.parse(e.data);
                if (frame.Op === 'stdout') {
                    that.term.write(frame.Data);
                }
            };
            that.terminalSocket.onclose = function() {
                console.log('close');
            };
            that.term.on('resize', () => {
                that.terminalSocket.send(JSON.stringify({
                Op: 'resize',
                Cols: term.cols,
                Rows: term.rows,
                }));
            });
            that.term.on('data', (data) => {
                that.terminalSocket.send(JSON.stringify({
                Op: 'stdin',
                Data: data,
                Cols: term.cols,
                Rows: term.rows,
                }));
            });
            });
      });
    },
    beforeDestroy () {
        this.terminalSocket.close()
        this.term.destroy()
    }
}
</script>

<style lang="less" scoped>

</style>
