<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="12">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>{{ $t('pages.websocketTool.broadcast.title') }}</span>
            <el-button style="float: right; padding: 3px; margin: 0 3px" type="success" @click="addRepository(socketSubForm)">{{ $t('pages.websocketTool.action.addRepository') }}</el-button>
            <el-button style="float: right; padding: 3px; margin: 0 3px" type="success" @click="sendMessage(socketSubForm)">{{ $t('pages.websocketTool.action.sendMessage') }}</el-button>
            <el-button style="float: right; padding: 3px; margin: 0 3px" type="warning" @click="subscribeSocket(socketSubForm)">{{ $t('pages.websocketTool.action.subscribeTopic') }}</el-button>
            <el-button style="float: right; padding: 3px; margin: 0 3px" type="danger" @click="disconnect(socketSubForm)">{{ $t('pages.websocketTool.action.disconnect') }}</el-button>
            <el-button style="float: right; padding: 3px; margin: 0 3px" type="primary" @click="createConnect(socketSubForm)">{{ $t('pages.websocketTool.action.connect') }}</el-button>
          </div>
          <div class="card-content">
            <div style="padding: 10px 80px;">
              {{ $t('pages.websocketTool.step.flow') }}
            </div>
            <el-form ref="socketSubForm" :model="socketSubForm" :rules="socketSubFormRules" label-width="120px">
              <el-form-item :label="$t('pages.websocketTool.form.socketEndpoint')" prop="socketEndpoint">
                <el-input v-model="socketSubForm.socketEndpoint" :placeholder="$t('pages.websocketTool.placeholder.socketEndpoint')" />
              </el-form-item>
              <el-form-item :label="$t('pages.websocketTool.form.subscribePath')" prop="subscribePatch">
                <el-input v-model="socketSubForm.subscribePatch" :placeholder="$t('pages.websocketTool.placeholder.subscribePath')" />
              </el-form-item>
              <el-form-item :label="$t('pages.websocketTool.form.sendEndpoint')" prop="sendEndpoint">
                <el-input v-model="socketSubForm.sendEndpoint" :placeholder="$t('pages.websocketTool.placeholder.sendEndpoint')" />
              </el-form-item>
              <el-form-item :label="$t('pages.websocketTool.form.myToken')" prop="meUserId">
                <el-input v-model="socketSubForm.meUserId" :placeholder="$t('pages.websocketTool.placeholder.myToken')" />
              </el-form-item>
              <el-form-item :label="$t('pages.websocketTool.form.content')" prop="content">
                <el-input
                  v-model="socketSubForm.content"
                  type="textarea"
                  :placeholder="$t('pages.websocketTool.placeholder.content')"
                  maxlength="300"
                  resize="none"
                  show-word-limit
                />
              </el-form-item>
              <el-form-item :label="$t('pages.websocketTool.form.repositoryEndpoint')" prop="repositoryEndpoint">
                <el-input v-model="socketSubForm.repositoryEndpoint" :placeholder="$t('pages.websocketTool.placeholder.repositoryEndpoint')" />
              </el-form-item>
              <el-form-item :label="$t('pages.websocketTool.form.repositoryData')" prop="repositoryData">
                <el-input
                  v-model="socketSubForm.repositoryData"
                  type="textarea"
                  :placeholder="$t('pages.websocketTool.placeholder.repositoryData')"
                  maxlength="300"
                  resize="none"
                  show-word-limit
                />
              </el-form-item>
              <el-form-item :label="$t('pages.websocketTool.form.statusDescription')">
                {{ socketSubForm.message }}
              </el-form-item>
              <el-form-item :label="$t('pages.websocketTool.form.content')">
                <div class="message-content">
                  <div v-for="(item, index) in socketSubForm.msgContents" :key="index">{{ item }}</div>
                </div>
              </el-form-item>
            </el-form>
          </div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>{{ $t('pages.websocketTool.direct.title') }}</span>
            <el-button style="float: right; padding: 3px; margin: 0 3px" type="success" @click="sendMessage(socketToUserForm)">{{ $t('pages.websocketTool.action.sendMessage') }}</el-button>
            <el-button style="float: right; padding: 3px; margin: 0 3px" type="warning" @click="subscribeSocket(socketToUserForm)">{{ $t('pages.websocketTool.action.subscribeTopic') }}</el-button>
            <el-button style="float: right; padding: 3px; margin: 0 3px" type="danger" @click="disconnect(socketToUserForm)">{{ $t('pages.websocketTool.action.disconnect') }}</el-button>
            <el-button style="float: right; padding: 3px; margin: 0 3px" type="primary" @click="createConnect(socketToUserForm)">{{ $t('pages.websocketTool.action.connect') }}</el-button>
          </div>
          <div class="card-content">
            <div style="padding: 10px 80px;">
              {{ $t('pages.websocketTool.step.flow') }}
            </div>
            <el-form ref="socketToUserForm" :model="socketToUserForm" :rules="socketToUserFormules" label-width="120px">
              <el-form-item :label="$t('pages.websocketTool.form.socketEndpoint')" prop="socketEndpoint">
                <el-input v-model="socketToUserForm.socketEndpoint" :placeholder="$t('pages.websocketTool.placeholder.socketEndpoint')" />
              </el-form-item>
              <el-form-item :label="$t('pages.websocketTool.form.subscribePrefix')" prop="subscribeUserPreffix">
                <el-input v-model="socketToUserForm.subscribeUserPreffix" :placeholder="$t('pages.websocketTool.placeholder.subscribePrefix')" />
              </el-form-item>
              <el-form-item :label="$t('pages.websocketTool.form.subscribePath')" prop="subscribePatch">
                <el-input v-model="socketToUserForm.subscribePatch" :placeholder="$t('pages.websocketTool.placeholder.subscribePath')" />
              </el-form-item>
              <el-form-item :label="$t('pages.websocketTool.form.sendEndpoint')" prop="sendEndpoint">
                <el-input v-model="socketToUserForm.sendEndpoint" :placeholder="$t('pages.websocketTool.placeholder.sendEndpoint')" />
              </el-form-item>
              <el-form-item :label="$t('pages.websocketTool.form.myToken')" prop="meUserId">
                <el-input v-model="socketToUserForm.meUserId" :placeholder="$t('pages.websocketTool.placeholder.myToken')" />
              </el-form-item>
              <el-form-item :label="$t('pages.websocketTool.form.targetUserId')" prop="targetUser">
                <el-input v-model="socketToUserForm.targetUser" :placeholder="$t('pages.websocketTool.placeholder.targetUserId')" />
              </el-form-item>
              <el-form-item :label="$t('pages.websocketTool.form.content')" prop="content">
                <el-input
                  v-model="socketToUserForm.content"
                  type="textarea"
                  :placeholder="$t('pages.websocketTool.placeholder.content')"
                  maxlength="300"
                  resize="none"
                  show-word-limit
                />
              </el-form-item>
              <el-form-item :label="$t('pages.websocketTool.form.statusDescription')">
                {{ socketToUserForm.message }}
              </el-form-item>
              <el-form-item :label="$t('pages.websocketTool.form.content')">
                <div class="message-content">
                  <div v-for="(item, index) in socketToUserForm.msgContents" :key="index">{{ item }}</div>
                </div>
              </el-form-item>
            </el-form>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import SockJS from 'sockjs-client'
import Stomp from 'stompjs'
export default {
  name: 'Dashboard',
  data() {
    return {
      socketSubForm: {
        // socketEndpoint: 'https://web.sugartimeapp.com/game_api/socket_stomp/game',
        socketEndpoint: 'http://192.168.31.179:9000/socket_stomp/game',
        subscribePatch: '/topic',
        sendEndpoint: '/app/send_topic',
        repositoryEndpoint: '/app/repository_add',
        content: '',
        meUserId: '',
        repositoryData: '',

        stompClient: null,
        message: '',
        msgContents: [],
        ruleFormName: 'socketSubForm'
      },

      socketToUserForm: {
        socketEndpoint: 'http://192.168.31.179:9000/socket_stomp/game',
        subscribeUserPreffix: '/user',
        subscribePatch: '/queue',
        sendEndpoint: '/app/send_queue',
        meUserId: '',
        targetUser: '',
        content: '',

        stompClient: null,
        message: '',
        msgContents: [],
        ruleFormName: 'socketToUserForm'
      }
    }
  },
  computed: {
    commonRules() {
      return [{ required: true, message: this.$t('pages.websocketTool.validation.requiredField'), trigger: 'blur' }]
    },
    socketSubFormRules() {
      return {
        socketEndpoint: this.commonRules,
        subscribePatch: this.commonRules,
        sendEndpoint: this.commonRules,
        meUserId: this.commonRules
      }
    },
    socketToUserFormules() {
      return {
        socketEndpoint: this.commonRules,
        subscribePatch: this.commonRules,
        sendEndpoint: this.commonRules,
        targetUser: this.commonRules,
        meUserId: this.commonRules,
        subscribeUserPreffix: this.commonRules
      }
    }
  },
  methods: {
    createConnect(form) {
      const that = this
      that.$refs[form.ruleFormName].validate(valid => {
        if (!valid) {
          console.log('error submit!!')
          return
        }
        // Configure the socket connection.
        const socket = new SockJS(form.socketEndpoint + `?token=${form.meUserId}&destination=${form.subscribePatch}`)
        // Configure the STOMP client.
        form.stompClient = Stomp.over(socket)
        // Connect the STOMP client.
        form.stompClient.connect({}, frame => {
          form.message = this.$t('pages.websocketTool.message.connected')
        })
      })
    },
    subscribeSocket(form) {
      if (!form.stompClient) {
        this.$opsMessage.fail(this.$t('pages.websocketTool.message.connectFirst'))
        return
      }
      form.message = form.subscribePatch
      // Subscribe to the message channel.
      form.stompClient.subscribe(form.subscribeUserPreffix ? form.subscribeUserPreffix + form.subscribePatch : form.subscribePatch, (responseBody) => {
        console.log('Received:', responseBody)
        var receiveMessage = JSON.parse(responseBody.body)
        form.msgContents.push(receiveMessage.content)
      })
    },
    disconnect(form) {
      if (!form.stompClient) {
        return
      }
      form.stompClient.disconnect(() => {
        form.message = this.$t('pages.websocketTool.message.disconnected')
      })
    },
    sendMessage(form) {
      if (!form.stompClient) {
        this.$opsMessage.fail(this.$t('pages.websocketTool.message.createFirst'))
        return
      }
      if (!form.content) {
        this.$opsMessage.fail(this.$t('pages.websocketTool.message.enterMessageContent'))
        return
      }
      // Prepare the message payload to send.
      var message = {
        destination: form.subscribePatch,
        content: form.content,
        targetUser: form.targetUser
      }
      console.log('Sending to endpoint:', form.sendEndpoint, 'Payload:', message)
      // Send the message.
      form.stompClient.send(form.sendEndpoint, {}, JSON.stringify(message))
    },
    addRepository(form) {
      if (!form.stompClient) {
        this.$opsMessage.fail(this.$t('pages.websocketTool.message.createFirst'))
        return
      }
      if (!form.repositoryData) {
        this.$opsMessage.fail(this.$t('pages.websocketTool.message.enterMessageContent'))
        return
      }
      // Prepare the repository payload to send.
      var message = {
        key: 'TEST',
        body: form.repositoryData
      }
      console.log('Sending to endpoint:', form.repositoryEndpoint, 'Payload:', message)
      // Send the message.
      form.stompClient.send(form.repositoryEndpoint, {}, JSON.stringify(message))
    }
  }
}
</script>

<style scoped lang="scss">
.box-card {
  margin-bottom: 10px;
  .card-content {
    padding: 20px;
  }
  .message-content {
      height: 200px;
      overflow: auto;
  }
}

</style>
