<html>

<head>
  <title>UA Smash 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 href="https://unpkg.com/primeicons/primeicons.css" rel="stylesheet">

  <!--
  <link rel="stylesheet" href="/stylesheets/style.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>

</head>

<body>
  <div id="app">

    <div class="container" style="margin-top: 50px;">

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

        <div class="col-6" style="padding-left: 50px; padding-right: 50px;">

          <div class="row mb-3" style="text-align: center">
            <h4>Demo Browser Source URL Generator</h4>
            <p>Paste your Start.gg API key to begin.</p>
          </div>

          <div class="row mb-3">
            <div class="col">
              <label for="api-key-input">Start.gg API Key</label>
              <div class="input-group mb-3">
                <input type="text" class="form-control" id="api-key-input" v-model="apiKey" @input="saveAPIKey">
                <button class="btn btn-outline-secondary" type="button" @click="saveAPIKey">Save Key</button> <!-- TODO: Make this less reliant on pasting the key to generate URLS. -->
              </div>
            </div>
          </div>

          <div class="row mb-3" v-if="apiKey.length > 0">
            <div class="col">
              <label>Winners "Best Of 5" Starting Point</label>
              <div v-for="option of finalsStartOptions" :key="option" class="field-radiobutton">
                <div class="form-check">
                  <input class="form-check-input" :id="'winner' + option" type="radio" name="winnerStart" :value="option" v-model="selectedWinnerBestOfStart">
                  <label class="form-check-label" :for="'winner' + option">&nbsp;<i>{{option}}</i></label>
                </div>
              </div>
            </div>

            <div class="col">
              <label>Losers "Best Of 5" Starting Point</label>
              <div v-for="option of finalsStartOptions" :key="option" class="field-radiobutton">
                <div class="form-check">
                  <input class="form-check-input" :id="'loser' + option" type="radio" name="loserStart" :value="option" v-model="selectedLoserBestOfStart">
                  <label class="form-check-label" :for="'loser' + option">&nbsp;<i>{{option}}</i></label>
                </div>
              </div>
            </div>
          </div>

          <div class="row mb-3" v-if="apiKey.length > 0">
            <div class="col">
              <label>Show Scores</label>
              <div class="form-check">
                <input class="form-check-input" id="showScore1" type="radio" name="showScore" value="Show" v-model="selectedShowScore">
                <label class="form-check-label" for="showScore1">&nbsp;<i>Show</i></label>
              </div>

              <div class="form-check">
                <input class="form-check-input" id="showScore2" type="radio" name="showScore" value="Hide" v-model="selectedShowScore">
                <label class="form-check-label" for="showScore2">&nbsp;<i>Hide</i></label>
              </div>
            </div>
          </div>

          <div class="row mb-3" v-if="apiKey.length > 0">
            <div class="col">
              <select class="form-select" aria-label="State selection" v-model="stateSelection" @change="loadTournamentList()">     
                <option value="" selected>Select a State</option>
                <template v-for="(item,index) in stateList">
                  <option :value="item.abbr">{{item.state}}</option>
                </template>
              </select>
            </div>
          </div>

          <div class="row mb-3" v-if="stateSelection != null">
            <div class="col">
              <select class="form-select" aria-label="Tournament selection" v-model="tournamentSelection" @change="getOverlayURLs()">     
                <option value="" selected>Select a Tournament</option>
                <template v-for="(item,index) in tournamentList">
                  <option :value="item">{{item.name}}</option>
                </template>
              </select>
            </div>
          </div>

          <div class="row">
            <div class="col">
              <template v-for="(item,index) in overlayURLs">
                <div class="mb-2">
                  <label for="'playeroverlay'+index">Player Overlay</label>
                  <input type="text" class="form-control" id="'playeroverlay'+index" :value="item">
                </div>
              </template>

              <template v-if="waitingOverlayURL.length > 0">
                <div class="mb-2">
                  <label for="waitingoverlay">Waiting Screen</label>
                  <input type="text" class="form-control" id="waitingoverlay" :value="waitingOverlayURL">
                </div>
              </template>

              <template v-if="waitingOverlayURL.length > 0">
                <div class="mb-2">
                  <label for="upcomingoverlay">Upcoming Matches</label>
                  <input type="text" class="form-control" id="upcomingoverlay" :value="upcomingOverlayURL">
                </div>
              </template>
            </div>
          </div>

        </div>

        <div class="col-6" style="padding-left: 50px; padding-right: 50px;">
          <div class="row mb-3" style="text-align: center">
            <h4>Advanced Application Sign In</h4>
          </div>

          <div class="row">
            <div class="card text-center p-0">
              <div class="card-body">

                <div class="row justify-content-center">
                  <div class="col-10" >
                    <form>
                      <div class="mb-3">
                        <label for="exampleFormControlInput1" class="form-label">Username</label>
                        <input v-model="username" type="text" class="form-control" id="exampleFormControlInput1" placeholder="">
                      </div>
                      <div class="mb-3">
                        <label for="exampleFormControlInput2" class="form-label">Password</label>
                        <input v-model="password" type="password" class="form-control" id="exampleFormControlInput2" placeholder="">
                      </div>
                      <button style="width: 100px;" type="submit" class="btn btn-primary" @click.prevent="submitLogInForm">
                        Log In
                      </button>
                      <button style="width: 100px;" type="submit" class="btn btn-link" @click.prevent="submitSignUpForm">
                        Sign Up
                      </button>
                    </form>
                  </div>
                </div>

              </div>
            </div>
          </div>

        </div>
      </div>

    </div>

  </div>
</body>

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

  createApp({
    data() {
      return {
        username: "",
        password: "",
        stateList: [
          { state: "Alabama", abbr: "AL" },
          { state: "Alaska", abbr: "AK" },
          { state: "Arizona", abbr: "AZ" },
          { state: "Arkansas", abbr: "AR" },
          { state: "California", abbr: "CA" },
          { state: "Colorado", abbr: "CO" },
          { state: "Connecticut", abbr: "CT" },
          { state: "Delaware", abbr: "DE" },
          { state: "Florida", abbr: "FL" },
          { state: "Georgia", abbr: "GA" },
          { state: "Hawaii", abbr: "HI" },
          { state: "Idaho", abbr: "ID" },
          { state: "Illinois", abbr: "IL" },
          { state: "Indiana", abbr: "IN" },
          { state: "Iowa", abbr: "IA" },
          { state: "Kansas", abbr: "KS" },
          { state: "Kentucky", abbr: "KY" },
          { state: "Louisiana", abbr: "LA" },
          { state: "Maine", abbr: "ME" },
          { state: "Maryland", abbr: "MD" },
          { state: "Massachusetts", abbr: "MA" },
          { state: "Michigan", abbr: "MI" },
          { state: "Minnesota", abbr: "MN" },
          { state: "Mississippi", abbr: "MS" },
          { state: "Missouri", abbr: "MO" },
          { state: "Montana", abbr: "MT" },
          { state: "Nebraska", abbr: "NE" },
          { state: "Nevada", abbr: "NV" },
          { state: "New Hampshire", abbr: "NH" },
          { state: "New Jersey", abbr: "NJ" },
          { state: "New Mexico", abbr: "NM" },
          { state: "New York", abbr: "NY" },
          { state: "North Carolina", abbr: "NC" },
          { state: "North Dakota", abbr: "ND" },
          { state: "Ohio", abbr: "OH" },
          { state: "Oklahoma", abbr: "OK" },
          { state: "Oregon", abbr: "OR" },
          { state: "Pennsylvania", abbr: "PA" },
          { state: "Rhode Island", abbr: "RI" },
          { state: "South Carolina", abbr: "SC" },
          { state: "South Dakota", abbr: "SD" },
          { state: "Tennessee", abbr: "TN" },
          { state: "Texas", abbr: "TX" },
          { state: "Utah", abbr: "UT" },
          { state: "Vermont", abbr: "VT" },
          { state: "Virginia", abbr: "VA" },
          { state: "Washington", abbr: "WA" },
          { state: "West Virginia", abbr: "WV" },
          { state: "Wisconsin", abbr: "WI" },
          { state: "Wyoming", abbr: "WY" }],
        stateSelection: "",
        tournamentList: [],
        tournamentSelection: null,
        playerOverlay: "overlay/players",
        waitingOverlay: "overlay/waiting",
        upcomingOverlay: "overlay/upcoming",
        selectedWinnerBestOfStart: 'Quarter-Final',
        selectedLoserBestOfStart: 'Quarter-Final',
        selectedShowScore: "Hide",
        finalsStartOptions : [
          'Round 1',
          'Round 2',
          'Round 3',
          'Round 4',
          'Round 5',
          'Quarter-Final',
          'Semi-Final',
          'Final',
          'Grand Final',
        ],
        overlayTypes: [0],
        overlayURLs: [],
        waitingOverlayURL: '',
        upcomingOverlayURL: '',
        apiKey: '',
      }
    },
    mounted() {

      const key = localStorage.getItem('apiKey')

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

    },
    methods: {
      async submitLogInForm() {
        if(this.username != null && this.password != null) {
          if(this.username.length > 0  && this.password.length > 0) {

            const data = {"username": this.username,"password": this.password};
            const path = window.location.origin

            try {
              const response = await fetch(path + '/users/login', {
                method: "post",
                headers: {
                  "Content-Type": "application/x-www-form-urlencoded",
                },
                body: new URLSearchParams(data),
              });

              if(response.status == 200) {
                const json = await response.json();
                window.location.href = json.redirectUrl;
              } else {
                alert('Username or password is incorrect.')
              }
            } catch (e) {
              alert('Login attempt failed.')
              //console.log(e)
            }

          } else {
            alert("Username and password cannot be blank.")
          }
        }
      },
      async submitSignUpForm() {
        if(this.username != null && this.password != null) {
          if(this.username.length > 0  && this.password.length > 0) {

            const data = {"username": this.username,"password": this.password};
            const path = window.location.origin

            try {
              const response = await fetch(path + '/users/signup', {
                method: "post",
                headers: {
                  "Content-Type": "application/x-www-form-urlencoded",
                },
                body: new URLSearchParams(data),
              });

              if(response.status == 200) {
                alert('Signup successful!')
              } else {
                alert('Signup unsuccessful.')
              }

            } catch (e) {
              alert('Signup attempt failed.')
              //console.log(e)
            }

          } else {
            alert("Username and password cannot be blank.")
          }
        }
      },
      async loadTournamentList() {
        try {
          if(this.stateSelection.length > 0) {

            const key = this.apiKey
            const stateAbbr = this.stateSelection
            const results = await StartGGAPI.queryTournaments(key,stateAbbr)
            this.tournamentList = results

          }
        } catch (e) {
          console.log(e)
        }
      },
      getOverlayURLs() {
        const slug = this.tournamentSelection.slug == null ? '' : this.tournamentSelection.slug

        this.overlayURLs = []
        for(var i = 0; i < this.overlayTypes.length; i++) {
          const url = window.location.origin + "/" + this.playerOverlay + "?" + new URLSearchParams({
            "type": this.overlayTypes[i],
            "poll": true,
            "winnerBestOfStart": this.selectedWinnerBestOfStart,
            "loserBestOfStart": this.selectedLoserBestOfStart,
            "showScores": this.selectedShowScore,
            "slug": slug,
            "startgg_key": this.apiKey,
          })

          this.overlayURLs.push(url)
        }

        this.waitingOverlayURL = window.location.origin + "/" + this.waitingOverlay + "?" + new URLSearchParams({
          "type": 0,
          "slug": slug,
          "startgg_key": this.apiKey,
        })

        this.upcomingOverlayURL = window.location.origin + "/" + this.upcomingOverlay + "?" + new URLSearchParams({
          "type": 0,
          "slug": slug,
          "startgg_key": this.apiKey,
        })

      },
      saveAPIKey() {
        localStorage.setItem('apiKey',this.apiKey)
      }
    },
    components: {

    }
  }).mount('#app')

</script>

</html>
