<html>

<head>
  <title>UA Smash Overlay Editor</title>

  <!-- Required meta tags -->
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <!-- Bootstrap CSS -->
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.9.1/font/bootstrap-icons.css">

  <link href="https://unpkg.com/primeicons/primeicons.css" rel="stylesheet">

  <link rel="stylesheet" href="/stylesheets/editor.css">

  <!-- jQuery first, then Popper.js, then Bootstrap JS -->
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.5/dist/umd/popper.min.js" integrity="sha384-Xe+8cL9oJa6tN/veChSP7q+mnSPaj5Bcu9mPX5F5xIGE0DVittaqT5lorf0EI7Vk" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/js/bootstrap.min.js" integrity="sha384-ODmDIVzN+pFdexxHEHFBQH3/9/vQ9uori45z4JjnFsRydbmQbmL5t1tQ0culUzyK" crossorigin="anonymous"></script>

  <script src="https://unpkg.com/vue@3"></script>

  <script src="/socket.io/socket.io.js"></script>

</head>

<body>
  <div id="app">

    <nav-bar :icon-url="navLogoUrl" :links="navLinks"></nav-bar>

    <div class="container" style="padding-bottom: 25px; padding-top: 15px">

      <div class="row justify-content-center">

        <div class="col-12 col-lg-6">
          <div class="row mb-2">
            <div class="col border rounded" style="background-color: white;">
              <form id="overlay-edit">
                <div class="row" style="margin-bottom: 25px;">
                  <h5>Player & Banner Update</h5>
                </div>
    
                <div class="row mb-2">
                  <div class="col" >
                    <label for="team-one-input">Left Team</label>
                    <input type="text" class="form-control" id="team-one-input" v-model="teamOne" placeholder="">
                  </div>
    
                  <div class="col">
                    <label for="team-two-input">Right Team</label>
                    <input type="text" class="form-control" id="team-two-input" v-model="teamTwo" placeholder="">
                  </div>
                </div>
    
                <div class="row mb-3">
                  <div class="col mb-2">
                    <div class="form-check form-check" v-for="(item, index) of scoreOptions" :key="item">
                      <input class="form-check-input" :id="'p1Score' + (index + 1)" type="radio" name="p1Score" :value="item.value" v-model="p1Score">
                      <label class="form-check-label" :for="'p1Score' + (index + 1)">{{item.name}}</label>
                    </div>
                  </div>
    
                  <div class="col">
                    <div class="form-check form-check" v-for="(item, index) of scoreOptions" :key="item">
                      <input class="form-check-input" :id="'p2Score' + (index + 1)" type="radio" name="p2Score" :value="item.value" v-model="p2Score">
                      <label class="form-check-label" :for="'p2Score' + (index + 1)">{{item.name}}</label>
                    </div>
                  </div>
                </div>
    
                <div class="row mb-3">
                  <h5>Event Banner</h5>
                </div>
    
                <div class="row mb-2">
                  <div class="col-6 col-md-4 mb-2">
                    <select class="form-select" aria-label="Bracket Type selection" v-model="bracketType">     
                      <option value="" selected>Bracket Type</option>
                      <template v-for="(item,index) in bracketList">
                        <option :value="item">{{item}}</option>
                      </template>
                    </select>
                  </div>
                  <div class="col-6 col-md-4 mb-2">
                    <select class="form-select" aria-label="Round Type selection" v-model="eventRound">     
                      <option value="" selected>Round Type</option>
                      <template v-for="(item,index) in roundList">
                        <option :value="item">{{item}}</option>
                      </template>
                    </select>
                  </div>
    
                  <div class="col-6 col-md-4 mb-2">
                    <select class="form-select" aria-label="Best Of selection" v-model="bestOf">     
                      <option value="" selected>Best Of</option>
                      <template v-for="(item,index) in matchList">
                        <option :value="item">{{item}}</option>
                      </template>
                    </select>
                  </div>
    
                </div>
    
                <div class="row justify-content-between pt-3">
                  <div class="col-8">
                    <button class="btn btn-outline-secondary" type="button" @click="submitOverlayForm" style="width: 125px;">Publish</button>
                    &nbsp;<button class="btn btn-outline-secondary" type="button" @click="clearOverlayForm" style="width: 125px;">Clear</button>
                  </div>
                </div>
              </form>
            </div>
          </div>
        </div>

      </div>

      <!-- TODO: Rebuild preview header? -->

    </div>

  </div>
</body>

<script type="module">
  import NavBar from '/javascripts/NavBar.js'
  import OverlayDataManager from '/javascripts/OverlayDataManager.js'
  import Editor from '/javascripts/Editor.mjs'

  const { createApp} = Vue

  const socket = io(window.location.origin, {
    reconnectionDelayMax: 10000,
    autoConnect: false,
  })

  socket.on("connect_error", (err) => {
    console.log("connect error")
  })

  socket.on("connect", () => {

  })

  socket.on("disconnect", () => {
    socket.connect();
  })

  socket.on("close", (reason) => {

  })

  addEventListener('pagehide', (event) => {
    socket.disconnect()
  })

  addEventListener('pageshow', (event) => {
    if(event.persisted) {
      socket.connect()

      /*

      OverlayDataManager.importKeyOrGenerate(editorApp.host+editorApp.port,<%= user.id %>,"players","Player Overlay").then((data) => {
        if(data.key_value.length > 0) {
          await socket.emit("unsubscribe",editorApp.playerRoom)

          editorApp.playerRoom = data.key_value
          socket.emit("subscribe",editorApp.playerRoom)
        }
      })

      */

    }
  })

  const editorApp = createApp({
    data() {
      return {
        navLogoUrl: '/fsmsmashlogo.png',
        navLinks:[],
        playerEntry: '',
        playerList: [],
        filteredPlayers: [],
        filteredBrackets: [],
        filteredRounds: [],
        teamOne: '',
        teamTwo: '',
        p1Score: "",
        p2Score: "",
        p1ScoreIncrement: 0,
        p2ScoreIncrement: 0,
        bracketType: "",
        eventRound: "",
        bestOf: "",
        playerRoom: "",
        socket: socket,
        scoreOptions: [
          { name: "-", value: "" },
          { name: "0", value: "0" },
          { name: "1", value: "1" },
          { name: "2", value: "2" },
          { name: "3", value: "3" },
          { name: "4", value: "4" },
        ],
        bracketList: [
          "Friendlies",
          "Pools",
          "Bracket",
          "Top 32",
          "Top 8",
        ],
        roundList: [
          "Round 1",
          "Round 2",
          "Round 3",
          "Round 4",
          "Round 5",
          "Winners Round 1",
          "Winners Round 2",
          "Winners Round 3",
          "Winners Round 4",
          "Winners Round 5",
          "Winners Quarter-Final",
          "Winners Semi-Final",
          "Winners Final",
          "Losers Round 1",
          "Losers Round 2",
          "Losers Round 3",
          "Losers Round 4",
          "Losers Round 5",
          "Losers Quarter-Final",
          "Losers Semi-Final",
          "Losers Final",
          "Grand Final",
          "Grand Final Reset",
        ],
        matchList: [
          "Best of 3",
          "Best of 5",
        ],
      }
    },
    mounted() {

      OverlayDataManager.importOverlayData(window.location.origin,<%= user.id %>,"players").then((data) => {
        if(data.key_value.length > 0) {
          this.playerRoom = data.key_value
          
          this.socket.connect()
          this.socket.emit("subscribe",data.key_value)
        } else {
          // TODO: Need to implement graceful failure.
        }
      })

      const playerList = localStorage.getItem('playerList')

      if(playerList != null){
        this.playerList = JSON.parse(playerList)
      }

      const playerEntry = localStorage.getItem('playerEntry')

      if(playerEntry != null) {
        this.playerEntry = playerEntry
      }

      const overlayData = localStorage.getItem('overlayData')

      if(overlayData != null){
        const parsedData = JSON.parse(overlayData)

        this.teamOne     = parsedData.teamOne.name
        this.p1Score     = parsedData.teamOne.score
        this.teamTwo     = parsedData.teamTwo.name
        this.p2Score     = parsedData.teamTwo.score
        this.bracketType = parsedData.bracketType
        this.eventRound  = parsedData.eventRound
        this.bestOf      = parsedData.bestOf
      }

    },
    methods: {
      async submitOverlayForm() {
        try {
          if (this.teamOne != null && this.p1Score != null && this.teamTwo != null && this.p2Score != null) {

            const form = Editor.getOverlayForm(
              this.teamOne,
              this.p1Score,
              this.teamTwo,
              this.p2Score,
              this.bracketType,
              this.eventRound,
              this.bestOf,
            );

            this.socket.emit("overlay-update", {content: form, to: this.playerRoom}, (response) => {
              console.log(response)
            })

            // TODO: Add confirmation to load data?

            this.p1ScoreIncrement = this.p1Score.value
            this.p2ScoreIncrement = this.p2Score.value

            localStorage.setItem('overlayData',JSON.stringify(form))

          } else {
            // TODO: Throw error?
          }
        } catch (e) {
          console.log(e)
        }
      },
      clearOverlayForm() {
        this.teamOne = ''
        this.teamTwo = ''
        this.p1Score = { name: "-", value: "" }
        this.p2Score = { name: "-", value: "" }

        this.bracketType = ""
        this.eventRound = ""
        this.bestOf = ""

        localStorage.removeItem('overlayData')
      },
      clearScoreForm() {
        this.p1ScoreIncrement = 0
        this.p2ScoreIncrement = 0
      },
    },
    computed: {

    },
    components: {
      NavBar
    },
  }).mount('#app')

</script>

</html>
