<script lang="ts">
import ritzenbergenlib from "../../ritzenbergenlib";
import "../../assets/css/bulitipp2.css";

export default {
  props: {
    token: {
      type: String,
      required: false,
    },
  },
  data() { 
    return {
      spieltag: "",
      vmodelspieltag: "",
      tipps: [
        new ritzenbergenlib.Tipp(null, null, null),
        new ritzenbergenlib.Tipp(null, null, null),
        new ritzenbergenlib.Tipp(null, null, null),
        new ritzenbergenlib.Tipp(null, null, null),
        new ritzenbergenlib.Tipp(null, null, null),
        new ritzenbergenlib.Tipp(null, null, null),
        new ritzenbergenlib.Tipp(null, null, null),
        new ritzenbergenlib.Tipp(null, null, null),
        new ritzenbergenlib.Tipp(null, null, null)
      ],
      disabled: false,
      schongetippt: true
    };
  },
  asyncComputed: {
    userinfo: {
      get() {
        if (this.token == null) return null;
        return fetch(
          ritzenbergenlib.RitzenbergenLib.api(
            "/bulitipp/userinfo.php?token=" + this.token
          )
        )
          .then((response) => response.json())
          .catch((error) => {
            console.error("Error fetching user info:", error);
            return null;
          });
      },
      default: null,
    },
    paarungen: {
      get() {
        if (this.spieltag == null) return null;
        return fetch(
          ritzenbergenlib.RitzenbergenLib.api(
            "/bulitipp/paarungen.php?spieltag=" + this.spieltag
          )
        )
          .then((response) => response.json())
          .then((response) => response.data)
          .then((response) =>
            response.map((el) => {
              return new ritzenbergenlib.Paarung(el[0], el[1], el[2]);
            })
          );
      },
      default: null,
    },
    maxtippspieltag: {
      get(){
        return fetch(
          ritzenbergenlib.RitzenbergenLib.api(
            "/bulitipp/maxtippspieltag.php"
          )
        )
          .then((response) => response.text())
          .then((text)=> parseInt(text))
      }
    },
    maxspieltag: {
      get(){
        return fetch(
          ritzenbergenlib.RitzenbergenLib.api(
            "/bulitipp/maxspieltag.php"
          )
        )
          .then((response) => response.text())
          .then((text)=> parseInt(text))
      }
    },
    mintippspieltag: {
      get(): number {
        if(this.maxspieltag==34){
          this.disabled = true;
          return 1;
        }else{
          this.disabled = false;
          return this.maxspieltag + 1;
        }
      },
      watch: ["maxspieltag"]
    },
    tippupdater:{
      get(){
        const params = new URLSearchParams({
          spieltag: this.spieltag.toString()
        });
        
        return fetch(
          ritzenbergenlib.RitzenbergenLib.api(
            "/bulitipp/tippsuser.php?" + params.toString()),
            {
              method: "GET",
              headers: {
                Authorization: "Bearer " + this.token,
              },
            }
          )
          .then((response) => response.json())
          .then((response) => {
            if (response.length > 0) {
              return response.map((el:any) => {
                if(el==null){
                  this.schongetippt = false;
                  return new ritzenbergenlib.Tipp(null, null, null);
                }
                this.schongetippt=true;
                return new ritzenbergenlib.Tipp(
                  el.paarung,
                  el.score1,
                  el.score2
                );
              });
            }
          }).then(response=>{
            this.tipps=response;
            return response;
          });
      },
      watch: ["spieltag"]
    },
    zeitzutippen: {
      get(){
        return fetch(
          ritzenbergenlib.RitzenbergenLib.api(
            "/bulitipp/zeitzutippen.php"
          )
        )
          .then((response) => response.json());
      }
    }
  },
  emits: ["logout"],
  methods: {
    getTeamImage(team: string) {
      return ritzenbergenlib.RitzenbergenLib.api(
        "/bulitipp/get-image.php?team=" + team
      );
    },
    async tippen(){
      this.tipps.forEach((tipp, i) => {
        tipp.paarung = this.paarungen[i];
      });
      
      const params = new URLSearchParams({
        spieltag: this.spieltag.toString(),
        tipps: JSON.stringify(this.tipps)
      });

      let result=await fetch(
        ritzenbergenlib.RitzenbergenLib.api("/bulitipp/tippeintragen.php?"+params.toString()),
        {
          method: "GET",
          headers: {
            Authorization: "Bearer " + this.token,
          },
        }
      );
      this.spieltag = "";
    }
  },
};
</script>
<template>
  <div>
    <div v-if="(spieltag == '' || spieltag == null) && userinfo != null">
      <h1>Moin {{ userinfo.username }}!</h1>
      <br />
			<h4 v-if="zeitzutippen!=null">Du hast noch <span v-if="zeitzutippen.days!=0">{{ zeitzutippen.days }} Tage und </span>{{ zeitzutippen.hours }} Stunden Zeit, den {{ zeitzutippen.spieltag }}. Spieltag zu tippen.</h4>
      <br />
      <div v-if="disabled">
        <h3>Gerade kann nicht getippt werden.</h3><br>
      </div>
      <form @submit.prevent="spieltag = parseInt(vmodelspieltag)">
        <input
          type="number"
          v-model="vmodelspieltag"
          :placeholder="'Spieltag (max: '+maxtippspieltag+')'"
          :min="mintippspieltag"
          :max="maxtippspieltag"
          required
          :disabled="disabled"
        />
        <input type="submit" value="Tippen" :disabled="disabled" />
        <br /><br />
        <input type="button" value="Ausloggen" @click="$emit('logout')" class="red-button" />
      </form>
    </div>
    <div class="tippenEintragen" v-else>
      <form @submit.prevent="tippen" id="mainform">
        <span class="paarung" v-for="(paarung,i) in paarungen" :key="paarung.id">
          <img :src="getTeamImage(paarung.heim)" alt="" />
          <span class="team-name">{{ paarung.heim }}</span>

          <input v-model="tipps[i].heim" type="number" min="0" class="score" required />
          <span class="vs"></span>
          <input v-model="tipps[i].gast" type="number" min="0" class="score" required />
          <span class="team-name">{{ paarung.gast }}</span>
          <img :src="getTeamImage(paarung.gast)" alt="" /><br />
        </span>
        <input type="submit" :value="schongetippt?'Tipps aktualisieren':'Tippen'" class="green-button"/>
        <br /><br />
        <input type="button" value="Abbrechen" @click="spieltag = ''" class="red-button" />
      </form>
    </div>
  </div>
</template>
<style scoped>
img {
  width: 30px;
}
</style>
