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

  <style>
    body {
      background-color: rgb(245, 245, 245);
      padding: 0px;
    }

    body form {
      padding-top: 12px;
      padding-bottom: 12px;
      padding-left: 20px;
      padding-right: 20px;
    }
  </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">

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

    <!--<p-toast></p-toast>-->

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

      <div class="row justify-content-around mb-2">
        
        <div class="col-5 border rounded" style="padding: 15px; background-color: white;">

          <div class="row mb-3">
            <h3>Configuration Settings</h3>
          </div>

          <div class="row">
            <div class="col-12">
              <h5>Logo</h5>
            </div>
            <div class="col-12">
              <p>Limit size to 300 x 200 for best results.</p>
            </div>
          </div>

          <div class="row mb-4">
            <div class="col-12 mb-4">

              <!--<p-fileupload 
                mode="basic" 
                :multiple="false"
                :with-credentials="true"
                name="files[]"
                :url="originURL + '/data/images/upload'"
                accept="image/png" 
                :max-file-size="1000000" 
                @upload="onUpload" 
                :auto="true" 
                choose-label="Browse">
              </p-fileupload>-->

              <input type="file" id="fileSelect" accept="image/png" @change="fileUpload" style="display:none" />
              <button id="fileSelectButton" class="btn btn-primary" type="button" @click="fileSelect">Upload Logo</button>

            </div>

            <div class="col-12 mb-2">
              <div class="form-check">
                <input class="form-check-input" id="logoChoice0" type="radio" name="logoChoice" value="" v-model="logoChoice">
                <label class="form-check-label" for="logoChoice0">&nbsp; None</label>
              </div>
            </div>

            <div class="col-12 mb-2" v-for="(url, index) of logoUrl" :key="url">
              <div class="form-check">
                <input class="form-check-input" :id="'logoChoice' + (index + 1)" type="radio" name="logoChoice" :value="url.value" v-model="logoChoice">
                <label class="form-check-label" :for="'logoChoice' + (index + 1)">&nbsp; <img v-if="url.src.length > 0" :src="url.src" style="height: 30px; background-color: gray;"/></label>
              </div>
            </div>
          </div>

          <div class="row">
            <div class="col">
              <label for="api-key-input"><h5>Start.gg API Key</h5></label>
            </div>
          </div>

          <div class="row mb-4">
            <div class="col">
              <div class="input-group mb-2">
                <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 class="form-check mb-2">
                <input class="form-check-input" id="binary" type="checkbox" name="binary" value="true" v-model="polling">
                <label class="form-check-label" for="binary">&nbsp; Automatic API polling</label>
              </div>
            </div>
          </div>

          <div class="row" v-if="apiKey.length > 0">
            <div class="col">
              <h5>Rules</h5>
            </div>
          </div>

          <div class="row mb-4" v-if="apiKey.length > 0">

            <div class="col-12 mb-3">
              <div class="input-group">Best of &nbsp;<input type="number" class="form-control" v-model="earlyMatches" style="max-width: 50px;"></div>
            </div>

            <div class="col-5 mb-3">
              <div class="input-group">Best of &nbsp;<input type="number" class="form-control" v-model="laterMatches" style="max-width: 50px;">&nbsp; at</div>
            </div>
            <div class="col-7">    
              <select class="form-select" aria-label="Winners Best Of selection" v-model="selectedWinnerBestOfStart">     
                <!--<option value="" selected>Winners Starting Point</option>-->
                <template v-for="(item,index) in finalsStartOptions">
                  <option :value="item">Winners {{item}}</option>
                </template>
              </select>
            </div>

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

            <div class="col-7">
              <select class="form-select" aria-label="Losers Starting Point" v-model="selectedLoserBestOfStart">     
                <!--<option value="" selected>Winners Starting Point</option>-->
                <template v-for="(item,index) in finalsStartOptions">
                  <option :value="item">Losers {{item}}</option>
                </template>
              </select>
            </div>
          </div>

          <div class="row mb-4" 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" v-if="apiKey.length > 0">
            <div class="col">
              <h5>Tournament</h5>
            </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-4" v-if="stateSelection != null">
            <div class="col-12 mb-2">
                <select class="form-select" aria-label="Tournament selection" v-model="tournamentSelection" @change="selectTournamentSlug()">     
                  <option value="" selected>Select a Tournament</option>
                  <template v-for="(item,index) in tournamentList">
                    <option :value="item">{{item.name}}</option>
                  </template>
                </select>
            </div>
            <div class="col-12">
              <input type="text" class="form-control" v-model="slug">
            </div>
          </div>

          <div class="row">
            <div class="col">
              <button 
              class="btn btn-primary" 
              type="button" 
              
              @click="submitSettings">Save</button>
            </div>
          </div>

        </div>

        <div class="col-6 border rounded" style="padding: 15px; background-color: white;">

          <div class="row mb-3">
            <h3>Browser Source URLs</h3>
          </div>

          <template v-for="(item, index) in overlayList">
            <div class="row mb-3">
              <div class="col-12">
                <label :for="'item'+index"><h6>{{item.name}}</h6></label>
                <div class="input-group mb-3">
                  <input type="text" class="form-control" :id="'item'+index" :value="getOverlayURL(item.path,{'type':item.type,'key':item.room,'startgg_key':apiKey})">
                  <button class="btn btn-outline-secondary" type="button" @click="regenerateKey(item.path, item.name)">Refresh</button>
                </div>
              </div>
            </div>
          </template>

        </div>

      </div>

    </div>

  </div>
</body>

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

  const dashboardApp = createApp({
    data() {
      return {
        userID: '',
        navLogoUrl: '/fsmsmashlogo.png',
        navLinks:[
          {url: '/editor', name: 'Manual Editor'},
          {url: '/striker', name: 'Stage Striker'},
        ],
        playerOverlayRoom: "",
        strikerOverlayRoom: "",
        overlayList: [],
        logoUrl: [],
        logoChoice: "",
        apiKey: '',
        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: null,
        tournamentList: [],
        tournamentSelection: null,
        slug: '',
        earlyMatches: 3,
        laterMatches: 5,
        selectedWinnerBestOfStart: 'Quarter-Final',
        selectedLoserBestOfStart: 'Quarter-Final',
        selectedShowScore: "Hide",
        finalsStartOptions : [
          'Round 1',
          'Round 2',
          'Round 3',
          'Round 4',
          'Round 5',
          'Round 6',
          'Round 7',
          'Round 8',
          'Quarter-Final',
          'Semi-Final',
          'Final',
          'Grand Final',
        ],
        polling: true,
      }
    },
    setup() {

      /*const toast = useToast();
			const onUpload = (event) => {
				toast.add({severity: 'info', summary: 'Success', detail: 'File Uploaded', life: 3000});

        const response = event.xhr.responseText
        if(response != null) {
          const data = JSON.parse(response)

          if(data.length > 0) {
            const file = data[0].filename == null ? '' : data[0].filename

            const item = dashboardApp.logoUrl.find(x => x.value.indexOf(file) > 0)
            if(item == null) {
              dashboardApp.logoUrl.push({src: file, value: '/data/images/get?user_id=<%= user.id %>' + "&filename=" + file})
            }
          }          
        }
			}

			return { onUpload };*/

    },
    mounted: async function(){

      this.userID = <%= user.id %>;

      const key = localStorage.getItem('apiKey')

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

      this.getAllLogosFromDB()

      const overlayData = await OverlayDataManager.importOverlayDataOrGenerate(window.location.origin,this.userID)
      overlayData.forEach(item => {
        this.overlayList.push(item)
      })

    },
    methods: {
      fileSelect() {

        const fileSelect = document.getElementById("fileSelect");
        fileSelect.click();

      },
      async fileUpload() {
        const fileInput = document.getElementById("fileSelect");
        const selectedFile = fileInput.files[0];

        if(selectedFile) {
          const formData = new FormData();
          formData.append("files[]", selectedFile);

          fetch(window.location.origin + '/data/images/upload', {
            method: "POST",
            body: formData
          })
          .then(response => response.json())
          .then(data => {

              if(data.length > 0) {
                const filename = data[0].filename == null ? '' : data[0].filename
                const item = dashboardApp.logoUrl.find(x => x.value.indexOf(filename) > 0)
                if(item == null) {
                  dashboardApp.getLogoFromDB(filename);
                }
              }

          })
          .catch(error => {
              console.error("Error uploading file:", error);
          });
        } else {
          //alert('Please select a file to upload.');
        }
      },
      getLogoFromDB(filename) {
        const imageFetchURL = '/data/images/get?user_id=' +dashboardApp.userID+ "&filename=" + filename
        
        fetch(imageFetchURL, {
          method: "get",
          headers: {
            "Content-Type": "image/png",
          },
        })
        .then(response => response.blob())
        .then(data => {

          const imageURL = URL.createObjectURL(data);
          dashboardApp.logoUrl.push({src: imageURL, value: imageFetchURL});

        })
        .catch(error => {
          console.error("Error fetching logo", error);
        });
      },
      getAllLogosFromDB () {

        try {
          const url = window.location.origin + '/data/images/all?' + new URLSearchParams({ "user_id": this.userID })

          fetch(url, {
            method: "get",
            headers: {
              "Content-Type": "application/json; charset=UTF-8",
            },
          })
          .then(response => response.json())
          .then(data => {

            for(var i = 0; i < data.length; i++) {
              dashboardApp.getLogoFromDB(data[i].image_name);
            }

          })
          .catch(error => {
              console.error("Error fetching all logos", error);
          });

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

      },
      getOverlayURL(overlay_path,params) {

        if(overlay_path != null && params != null) {
          return window.location.origin + "/overlay/" + overlay_path + "?" + new URLSearchParams(params)
        } else {
          return ''
        }

      },
      selectTournamentSlug() {
        if(this.tournamentSelection != null) {
          this.slug = this.tournamentSelection.slug
        }
      },
      async regenerateKey(overlay_path,overlay_name) {
        OverlayDataManager.regenerateOverlayKey(window.location.origin,dashboardApp.userID,overlay_path,overlay_name).then((data) => {
          const url = this.overlayList.find(x => x.path == data.overlay_path)
          if(url != null){
            url.path = data.overlay_path
            url.name = data.overlay_name
            url.room = data.key_value
          }
        })
      },
      saveAPIKey() {
        localStorage.setItem('apiKey',this.apiKey)
        //this.loadTournamentList()
      },
      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)
        }
      },
      async submitSettings() {
        
        const settings = {
          poll:this.polling,
          earlyMatches: this.earlyMatches,
          laterMatches: this.laterMatches,
          winnerBestOfStart: this.selectedWinnerBestOfStart,
          loserBestOfStart: this.selectedLoserBestOfStart,
          showScores: this.selectedShowScore,
          slug: this.slug,
          logoChoice: this.logoChoice,
        }

        if(this.slug.length > 0) {
          const result = await OverlayDataManager.saveOverlaySettings(window.location.origin,dashboardApp.userID,settings)
          
          if(result) {
            alert('Settings successfully saved.')
          } else {
            alert('Error occured while saving settings.')
          }

        } else {
          alert('Please choose a tournament.')
        }

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

</script>

</html>
