<html>

<head>
  <title>UA Smash Stage Striker</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/striker.css">

  <style>
    @media (min-width: 800px) {
      .modal {
        --bs-modal-width: 95%;
      }
    }
  </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 class="navbar navbar-expand-sm navbar-dark">
      <div class="container-fluid" style="margin-top: 75px;">
        <a class="navbar-brand pt-1 pl-2" href="#" disabled>
          <img
            :src="navLogoUrl"
            alt=""
            height="30"
          />
        </a>

        <button
          class="navbar-toggler"
          type="button"
          data-bs-toggle="collapse"
          data-bs-target="#navbarNavAltMarkup"
          aria-controls="navbarNavAltMarkup"
          aria-expanded="false"
          aria-label="Toggle navigation"
        >
          <span class="navbar-toggler-icon"></span>
        </button>

        <div class="collapse navbar-collapse" id="navbarNavAltMarkup">
          <div class="navbar-nav me-auto m-2">
            <button
              class="btn btn-sm btn-light"
              type="button"
              style="width: 125px"
              @click="resetActivityAndReloadStages()"
            >
              RESET
            </button>

            <button
              class="btn btn-sm btn-dark"
              type="button"
              style="width: 125px"
              @click="toggleStrikerConfig()"
            >
              SETTINGS
            </button>
          </div>

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

    <div id="config-modal" class="modal" tabindex="-1" aria-labelledby="config-modal-label" aria-hidden="true">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">

            <ul class="nav nav-underline">
              <li class="nav-item">
                <a class="nav-link active" aria-current="page" href="#">Stage Selection</a> <!-- TODO: Settings tab toggle. -->
              </li>
            </ul>

            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>
          <div class="modal-body">

            <div class="container-fluid" style="overflow-y: auto;">
              <form>
                <div class="row mb-2">
                  <template v-for="(item,index) in stageNameList">

                    <div class="col-12 col-lg-6">
                      <div class="row">
                        <div class="col-12 col-lg-4">
                          <p>{{item}}</p>
                        </div>
      
                        <div class="col-6 col-lg-4">
                          <div class="form-check mb-2">
                            <input class="btn-check" type="checkbox" :value="item" :id="'starter-selection' + index" v-model="starterSelection">
                            <label class="btn btn-outline-dark" :for="'starter-selection' + index" style="min-width: 100%;">Starter</label>
                          </div>
                        </div>
                        <div class="col-6 col-lg-4">
                          <div class="form-check mb-2">
                            <input class="btn-check" type="checkbox" :value="item" :id="'counterpick-selection' + index" v-model="counterpickSelection">
                            <label class="btn btn-outline-dark" :for="'counterpick-selection' + index" style="min-width: 100%;">Counterpick</label>
                          </div>
                        </div>
                      </div>
                    </div>
                    
                  </template>
  
                  <!--<div class="col-4 mb-3">
                    <h4>Starter Selection</h4>
                    <template v-for="(item,index) in stageNameList">
                      <div class="form-check mb-2">
                        <input class="btn-check" type="checkbox" :value="item" :id="'starter-selection' + index" v-model="starterSelection">
                        <label class="btn btn-outline-dark" :for="'starter-selection' + index" style="width: 250px; padding: 12px;">{{item}}</label>
                      </div>
                    </template>
                  </div>
                  <div class="col-4 mb-3">
                    <h4>Counterpick Selection</h4>
                    <template v-for="(item,index) in stageNameList">
                      <div class="form-check mb-2">
                        <input class="btn-check" type="checkbox" :value="item" :id="'counterpick-selection' + index" v-model="counterpickSelection">
                        <label class="btn btn-outline-dark" :for="'counterpick-selection' + index" style="width: 250px; padding: 12px;">{{item}}</label>
                      </div>
                    </template>
                  </div>-->
                </div>

                <div class="row mb-2">
                  <div class="col-10">
                    <button class="btn btn-dark" type="button" @click="saveStrikerConfig()" style="width: 125px">Save</button>
                    &nbsp;<button class="btn btn-outline-dark" type="button" @click="clearConfigStageSelections()" style="width: 125px">Clear</button>
                  </div>
                </div>
              </form>
            </div>

          </div>
          <!--<div class="modal-footer">S
          </div>-->
        </div>
      </div>
    </div>

    <div class="container-md mt-2 mb-2">
      <div class="row row-cols-2 row-cols-sm-4 row-cols-lg-5 rounded" style="overflow-y: auto; overflow-x: hidden">

        <transition-group name="fade">
          <template v-for="(item, index) in options" v-bind:key="item">

            <div class="col p-1" >
              <div class="card h-100 shadow text-center border-secondary" :class="{ 'bg-secondary text-light' : item.choice == Choice.Strike }">
                <card-header :item="item" :url="getImageURL(item.stageName)"></card-header>
                <card-body :item="item"></card-body>

                <div class="card-footer p-2" :class="{ 'border-light': item.choice == Choice.None, 'border-dark' : item.choice == Choice.Strike }">
                  <div class="row justify-content-center" v-if="item.choice == Choice.None">
                    <div class="col-6 p-0">
                      <!-- <button class="btn btn-light text-danger" type="button" @click="pickStage(index, false)" style="font-size: 16pt">
                        <i class="bi bi-x-circle-fill"></i>
                      </button>-->
                      <button class="btn btn-outline-danger" type="button" @click="pickStage(index, false)" style="font-size: 10pt; height: 40px; width: 75px;">
                        STRIKE
                      </button>
                    </div>
                    <div class="col-6 p-0">
                      <!-- <button class="btn btn-light text-primary" type="button" @click="pickStage(index, true)" style="font-size: 16pt">
                        <i class="bi bi-check-circle"></i>
                      </button>-->
                      <button class="btn btn-outline-primary" type="button" @click="pickStage(index, true)" style="font-size: 10pt; height: 40px; width: 75px;">
                        PICK
                      </button>
                    </div>
                  </div>

                  <div class="row justify-content-center" v-if="item.choice == Choice.Strike">
                    <div class="col">
                      <!-- <button class="btn btn-dark text-light" type="button" @click="undoChoice(item.stageName)" style="font-size: 16pt">
                        <i class="bi bi-arrow-counterclockwise"></i>
                      </button>-->
                      <button class="btn btn-outline-light" type="button" @click="undoChoice(item.stageName)" style="font-size: 10pt; height: 40px; width: 75px;">
                        UNDO
                      </button>
                    </div>
                  </div>
                </div>
              </div>
            </div>

          </template>
        </transition-group>

      </div>

      <template v-for="(record, index) in previousChoices" v-bind:key="record">
        <p style="color: white; margin-top: 15px">Set {{ index + 1 }}</p>
        <div class="row row-cols-2 row-cols-sm-4 row-cols-lg-5 rounded">
          <template v-for="item in record" v-bind:key="item">
            <div class="col p-1">

              <stage-card-small :item="item" :url="getImageURL(item.stageName)"></stage-card-small>

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

  </div>
</body>

<script type="module">
  import Striker from '/javascripts/Striker.mjs'

  import CardHeader from '/javascripts/CardHeader.js'
  import CardBody from '/javascripts/CardBody.js'
  import StageCardSmall from '/javascripts/StageCardSmall.js'

  import Stage from '/javascripts/Stage.js'
  import OverlayDataManager from '/javascripts/OverlayDataManager.js'

  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()
    }

  })

  const editorApp = createApp({
    data() {
      return {
        navLogoUrl: '/fsmsmashlogo.png',
        stageImageURLs: {},
        stageNameList: [],
        starterSelection: [],
        counterpickSelection: [],
        strikerRoom: "",
        configModal: null,
        options: [],
        choices: [],
        previousChoices: [],
        turns: 0,
        socket: socket,
        davesRule: true,
        Choice : {
          Pick: 'PICK',
          Strike: 'STRIKE',
          None: ''
        },
      }
    },
    mounted() {
      
      this.loadConfigStageList()

      this.resetOptionsAndChoices()
      this.loadStageSelectionsFromDB()

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

      var configModal = document.getElementById("config-modal");
      this.configModal = new bootstrap.Modal(configModal, {});

    },
    methods: {
      getNumberOfChoices() {
        if (this.choices != null) {
          return this.choices.length
        } else {
          return 0
        }
      },
      getImageURL(stageName) {
        if (this.stageImageURLs != null && stageName != null) {
          return this.stageImageURLs[stageName]
        } else {
          // TODO: Return placeholder image.
          return "./pexels-gradienta-6985001.jpeg"
        }
      },
      async loadConfigStageList() {
        try {
          const url = window.location.origin + '/data/stages'
          const response = await fetch(url, {
            method: "get",
            headers: {
              "Content-Type": "application/json; charset=UTF-8",
            },
          })

          if(response.ok) {
            const results = await response.json()
            const stageListData = []
            const stageImgURLData = {}

            for (let i = 0; i < results.length; i++) {
              stageListData.push(results[i].stage_name)
              stageImgURLData[results[i].stage_name] = "/images/stages/" + results[i].image_url
            }

            this.stageNameList = stageListData
            this.stageImageURLs = stageImgURLData
          }
        } catch (e) {
          console.log(e)
        }
      },
      pickStage(index, pick) {
        if (this.options != null && this.options.length > 0) {
          if(this.choices == null) {
            this.choices = []
          }
          if (pick) {
            Striker.pick(this.options,this.choices,index,this.davesRule)

            const stages = this.choices
            this.previousChoices.push(stages)
            this.submitStageStrikes(stages)

            this.choices = []

            if(this.turns == 0) {
              this.options = Striker.addToOptionsList(this.options,this.counterpickSelection,'COUNTERPICK')
            }
            this.turns++
          } else {
            Striker.strike(this.options,this.choices,index)
          }
        }
      },
      undoChoice(stageName) {
        if (this.choices != null && this.options != null) {
          if (this.choices.length > 0) {
            Striker.undo(this.options,this.choices,stageName)
          }
        }
      },
      async submitStageStrikes(stages) {
        try {
          if (this.strikerRoom != null) {
            const data = Striker.createStageStrikesForm(stages)

            socket.emit("striker-update", {
              content: data,
              to: this.strikerRoom,
            });
          }
        } catch (e) {
          console.log(e)
        }
      },
      resetOptionsAndChoices() {
        this.options = []
        this.previousChoices = []
        this.choices = []
        this.turns = 0
      },
      resetActivityAndReloadStages() {
        this.resetOptionsAndChoices()
        this.loadStageSelections()
      },
      toggleStrikerConfig() {
      
        this.configModal.toggle();
        
      },
      saveStrikerConfig() {
        var stageSelections = []

        try {
          if (this.starterSelection != null && this.counterpickSelection != null) {
            stageSelections = Striker.createOptionsList(this.starterSelection,'STARTER')

            this.toggleStrikerConfig()
            this.resetOptionsAndChoices()

            this.saveStageSelectionsToDB(Striker.createCombinedOptionsList(this.starterSelection,this.counterpickSelection))
          }
        } catch(e) {
          console.log(e)
        }

        this.options = stageSelections;
      },
      clearConfigStageSelections() {
        this.starterSelection = []
        this.counterpickSelection = []
      },
      loadStageSelections() {
        if (this.starterSelection != null) {
          if (this.starterSelection.length > 0) {

            const data = Striker.createOptionsList(this.starterSelection,'STARTER')
            this.options = data

          } else {
            this.loadStageSelectionsFromDB()
          }
        } else {
          this.loadStageSelectionsFromDB()
        }
      },
      async saveStageSelectionsToDB(stage_list) {
        try {
          const url = window.location.origin + '/data/stage_lists/save_list'
          const response = await fetch(url, {
            method: "post",
            headers: {
              "Content-Type": "application/json; charset=UTF-8",
            },
            body: JSON.stringify({"user_id":<%= user.id %>,"stage_list":JSON.stringify(stage_list)})
          });

          if(response.ok) {
            const results = await response.json()
          }

        } catch (e) {
          console.log(e)
        }
      },
      async loadStageSelectionsFromDB() {
        try {
          const url = window.location.origin + '/data/stage_lists/load_list'
          const response = await fetch(url, {
            method: "post",
            headers: {
              "Content-Type": "application/json; charset=UTF-8",
            },
            body: JSON.stringify({"user_id":<%= user.id %>})
          });

          if(response.ok) {
            const results = await response.json()

            if(results.length > 0) {
              if(results[0].stage_list != undefined) {
                this.starterSelection = []
                this.counterpickSelection = []

                for(var i = 0; i < results[0].stage_list.length; i++){
                  const stageName = results[0].stage_list[i].stageName
                  if(results[0].stage_list[i].order == 'STARTER') {
                    this.starterSelection.push(stageName)
                  } else {
                    this.counterpickSelection.push(stageName)
                  }
                }

                this.options = Striker.createOptionsList(this.starterSelection,'STARTER')
              }
            }

          }

        } catch (e) {
          console.log(e)
        }
      },
    },
    computed: {
      
    },
    components: {
      CardHeader,
      CardBody,
      StageCardSmall
    },
  }).mount('#app')

</script>

</html>
