<html>

<head>
  <title>UA Smash Player Overlay</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 rel="stylesheet" href="/stylesheets/players.css">

  <style>
    body {
      background-color: rgba(0, 0, 0, 0);
      margin: 0px auto;
      overflow: hidden;
    }
  </style>

  <!-- 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">

      <div class="container-fluid" style="width: 1920px; height: 1080px;">

        <gameplay-overlay v-if="type == 0"
        :logo-choice="logoChoice"
        :p1name="p1Name"
        :p2name="p2Name"
        :showscore="showScores"
        :p1score="p1Score"
        :p2score="p2Score"
        :eventround="eventRound"
        :bestof="bestOf"
        :bracketType="bracketType"
        :p1members="p1.members"
        :p2members="p2.members"
        > </gameplay-overlay>

        <div class="row mt-3 justify-content-center" v-if="type == 1">
          
          <div class="col-1 shadow" style="background-color: rgba(0, 0, 0, 0.8); color: white; font-size: 24pt; border-radius: 50px 0 0 50px; font-weight: bold;">
            <div class="row p-2" style="text-align: right;">
              <p class="m-0">{{p1Name}}</p>
            </div>
          </div>
          <div class="col-1 shadow" style="background-color: rgba(0, 0, 0, 0.8); color: white; font-size: 24pt; border-radius: 0 50px 50px 0; font-weight: bold;">
            <div class="row p-2 m-0">
              <p class="m-0">{{p1Score}}</p>
            </div>
          </div>

          <div class="col-1"></div>

          <div class="col-1 shadow" style="background-color: rgba(0, 0, 0, 0.8); color: white; font-size: 24pt; border-radius: 50px 0 0 50px; font-weight: bold;">
            <div class="row p-2 m-0" style="text-align: right;">
              <p class="m-0">{{p2Name}}</p>
            </div>
          </div>
          <div class="col-1 shadow" style="background-color: rgba(0, 0, 0, 0.8); color: white; font-size: 24pt; border-radius: 0 50px 50px 0; font-weight: bold;">
            <div class="row p-2 m-0">
              <p class="m-0">{{p2Score}}</p>
            </div>
          </div>

        </div>

      </div>

    </div>

  </div>
</body>

<script type="module">
  import GameplayOverlay from '/javascripts/GameplayOverlay.js'
  import StartGGAPI from '/javascripts/StartGGAPI.js'
  import OverlayDataManager from '/javascripts/OverlayDataManager.js'
  const { createApp } = Vue

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

  socket.on("overlay-push", ({ content, from }) => {
    try {

      playerOverlayApp.setOverlayValues(content["teamOne"],content["teamTwo"],content["bracketType"],content["eventRound"],content["bestOf"])
      playerOverlayApp.saveDataToSessionStorage()

    } catch(e) {
      console.log(e)
    }
  })

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

  const playerOverlayApp = createApp({
    data() {
      return {
        p1: {},
        p2: {},
        p1Name: "",
        p2Name: "",
        p1Score: "",
        p2Score: "",
        bracketType: "",
        eventRound:"",
        bestOf:"",
        socket: socket,
        type: 0,
        poll: false,
        earlyMatches: "",
        laterMatches: "",
        winnerBestOfStart: 5,
        loserBestOfStart: 5,
        finalsOrder : {
          'Round 1':0,
          'Round 2':1,
          'Round 3':2,
          'Round 4':3,
          'Round 5':4,
          'Round 6':5,
          'Round 7':6,
          'Round 8':7,
          'Quarter-Final':8,
          'Semi-Final':9,
          'Final':10,
          'Grand Final':11
        },
        apiKey: null,
        slug: null,
        room: null,
        logoChoice: '',
        showScores: "Hide",
      }
    },
    mounted() {

      this.loadDataFromSessionStorage()

      const urlParams = new URLSearchParams(window.location.search)
      const type = urlParams.get('type')
      const key = urlParams.get('key')
      const startgg_key = urlParams.get('startgg_key')

      if(type != null) {
        this.type = type
      }
      if(key != null) {
        this.room = key
      }
      if(startgg_key != null) {
        this.apiKey = startgg_key
      }

      if(this.room != null) {

        OverlayDataManager.importOverlaySettings(window.location.origin,this.room).then((data) => {

          if(data.settings != null) {

            this.poll = data.settings.poll

            this.earlyMatches = "Best of " + data.settings.earlyMatches
            this.laterMatches = "Best of " + data.settings.laterMatches

            this.winnerBestOfStart = this.finalsOrder[data.settings.winnerBestOfStart] == null ? 8 : this.finalsOrder[data.settings.winnerBestOfStart]
            this.loserBestOfStart = this.finalsOrder[data.settings.loserBestOfStart] == null ? 8 : this.finalsOrder[data.settings.loserBestOfStart]
            this.showScores = data.settings.showScores
            this.slug = data.settings.slug
            this.logoChoice = data.settings.logoChoice

            if(data.settings.logoChoice.length > 0){

              const imageResponse = fetch(data.settings.logoChoice, {
                method: "get",
                headers: {
                  "Content-Type": "image/png",
                },
              }).then((response) => {
                if (!response.ok) {
                  throw new Error('Network response was not ok');
                }
                return response.blob()
              }).then((blob) => {
                const imageURL = URL.createObjectURL(blob)
                this.logoChoice = imageURL
              })
              .catch((error) => {
                console.error('Fetch error:', error)
              })

            } else {
              this.logoChoice = ""
            }

            try {

              if(this.poll && this.apiKey != null && this.slug != null){

                this.pollStartGGAPI()
                setInterval(function(){
                  playerOverlayApp.pollStartGGAPI()
                }, 5000)

              } else {
                this.connectSocketToRoom(this.room)
              } 

            } catch(e) {
              alert(e)
            }

          } else {
            alert("Unable to load configuration settings or required URL parameters missing.")
          }

        })

      } else {
        
        this.poll = urlParams.get('poll') == null ? false : urlParams.get('poll');
        this.winnerBestOfStart = urlParams.get('winnerBestOfStart') == null ? 8 : this.finalsOrder[urlParams.get('winnerBestOfStart')]
        this.loserBestOfStart = urlParams.get('loserBestOfStart') == null ? 8 : this.finalsOrder[urlParams.get('loserBestOfStart')]
        this.showScores = urlParams.get('showScores') == null ? "Hide" : urlParams.get('showScores')
        this.slug = urlParams.get('slug')

        if(this.poll && this.apiKey != null && this.slug != null){

          try {

            this.pollStartGGAPI()
            setInterval(function(){
              playerOverlayApp.pollStartGGAPI()
            }, 5000);

          } catch (e) {
            alert(e)
          }

        } else {
          alert("Required URL parameters missing.")
        }

      }

    },
    methods : {
      connectSocketToRoom(room) {
        if(room != null) {
          this.socket.connect()
          this.socket.emit("subscribe",room)
        }
      },
      async pollStartGGAPI() {
        try {
          const data = await StartGGAPI.queryStreamQueue(this.apiKey,this.slug)

          if(data.length == 0) {

            this.setOverlayValues({},{},'','','')
            this.saveDataToSessionStorage()

          } else {

            var nextSet = null

            var previousStartedAt = 0
            data.forEach((set) => {
              if(set.state == 2) {
                if(set.startedAt > previousStartedAt) {
                  nextSet = set
                }
                previousStartedAt = set.startedAt
              }
            })

            if(nextSet != null){
              const eventRound = nextSet.fullRoundText == null ? '' : nextSet.fullRoundText
              const order = this.finalsOrder[eventRound.replace(/Winners |Losers /g,'')]
              var bestOfValue = this.earlyMatches

              if(order != null) {
                if(eventRound.indexOf('Winner') >= 0) {
                  if(order >= this.winnerBestOfStart) {
                    bestOfValue = this.laterMatches
                  }
                } else {
                  if(order >= this.loserBestOfStart) {
                    bestOfValue = this.laterMatches
                  }
                }
              }

              this.setOverlayValues(nextSet.teamOne,nextSet.teamTwo,nextSet.phaseName,eventRound,bestOfValue)
              this.saveDataToSessionStorage()
            } else {
              this.setOverlayValues({},{},'','','')
              this.saveDataToSessionStorage()
            }

          }

        } catch(e) {
          console.log(e)
        }
      },
      setOverlayValues(teamOne,teamTwo,bracketType,eventRound,bestOf) {

        if(teamOne != null) {
          if(teamOne.members != null) {
            if(teamOne.members.length > 1) {
              teamOne.members = []
            }
          }
        }
        if(teamTwo != null) {
          if(teamTwo.members != null) {
            if(teamTwo.members.length > 1) {
              teamTwo.members = []
            }
          }
        }

        this.p1 = teamOne == null ? {} : teamOne
        this.p2 = teamTwo == null ? {} : teamTwo

        this.p1Name = this.p1.name == null ? "" : this.p1.name
        this.p1Score = this.p1.score == null ? 0 : this.p1.score

        this.p2Name = this.p2.name == null ? "" : this.p2.name
        this.p2Score = this.p2.score == null ? 0 : this.p2.score

        this.bracketType = bracketType == null ? "" : bracketType.toUpperCase()
        this.eventRound = eventRound == null ? "" : eventRound.toUpperCase()
        this.bestOf = bestOf == null ? "" : bestOf.toUpperCase()
      },
      saveDataToSessionStorage() {
        sessionStorage.setItem("teamOne",JSON.stringify(this.p1))
        sessionStorage.setItem("teamTwo",JSON.stringify(this.p2))

        sessionStorage.setItem("bracketType",this.bracketType)
        sessionStorage.setItem("eventRound",this.eventRound)
        sessionStorage.setItem("bestOf",this.bestOf)
      },
      loadDataFromSessionStorage() {

        const teamOne = sessionStorage.getItem("teamOne") == null ? {} : JSON.parse(sessionStorage.getItem("teamOne"))
        const teamTwo = sessionStorage.getItem("teamTwo") == null ? {} : JSON.parse(sessionStorage.getItem("teamTwo"))

        this.setOverlayValues(teamOne,teamTwo,sessionStorage.getItem("bracketType"),sessionStorage.getItem("eventRound"),sessionStorage.getItem("bestOf"))

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

</script>

</html>
