<script lang="js">
import Navbar from "../components/Navbar.vue";
import MyFooter from "../components/MyFooter.vue";
import Modal from "../components/Modal.vue";
import Uebersicht from "../components/bulitipp/Uebersicht.vue";
import Rangliste from "../components/bulitipp/Rangliste.vue";
import Paarungsergebnisse from "../components/bulitipp/Paarungsergebnisse.vue";
import Tabelle from "../components/bulitipp/Tabelle.vue";
import RitzenbergenLib from "../ritzenbergenlib.ts";
import SpieltagSumme from "../ritzenbergenlib.ts";
import Loading from "../components/bulitipp/Loading.vue";
import $ from "jquery";
import Tippen from "../components/bulitipp/Tippen.vue";
import TippenEinloggen from "../components/bulitipp/TippenEinloggen.vue";

export default {
  components: {
    Navbar,
    MyFooter,
    Modal,
    Uebersicht,
    Rangliste,
    Paarungsergebnisse,
    Tabelle,
    Loading,
    Tippen,
    TippenEinloggen
  },
	created(){
		RitzenbergenLib.RitzenbergenLib.checkInternetConnection().then((result)=>{
				if(!result) this.$router.push("/");
		});
	},
  asyncComputed: {
    users: {
      get(){
        return fetch(RitzenbergenLib.RitzenbergenLib.api("/bulitipp/get-users.php"))
        .then((response) => response.json())
        .then((result2) => {
          if(result2.reload) this.update();
          return result2.data;
        })
        .then((result) => {
          result.forEach((user, i) => {
              let sum = 0;
              this.ts.forEach((spieltag) => {
                let points = spieltag.find((element) => {
                  return element.user.id === user.id;
                });
                sum += points.tsPoints;
              });
              user.points = sum;
            });
            return result;
        })
        .then((result) => {
          return result.map(el => new RitzenbergenLib.User(el.name,el.kuerzel, el.points, el.id));
        })
				//.then((result)=>result.filter((el)=>(el.points>0&&maxspieltag>=2)))
        .catch((error) => {
          return null;
        });
      },
      default: [],
      watch: ["ts"]
    },
    ts: {
      get() {
        return fetch(RitzenbergenLib.RitzenbergenLib.api("/bulitipp/ts.php"))
        .then((response) => response.json())
        .then((result2) => {
          if(result2.reload) this.update();
          return result2.data;
        })
        .then((result)=>{
          result.map(element => element.map((element) => {

            element.user=new RitzenbergenLib.User(element.user.name, element.user.kuerzel,0, element.user.id);

            return element;
          }));
          return result;
        })
        .then((result)=>result.map((el) => el.map((el)=> new RitzenbergenLib.SpieltagSumme(el.user,el.points))));
      },
      default: []
    },
    saison:{
      get(){
        return fetch(RitzenbergenLib.RitzenbergenLib.api("/bulitipp/saison.php"))
        .then((response) => response.text())
       .then((result)=> parseInt(result));
      },
      default: ""
    },
    maxspieltag: {
      get(){
        return fetch(RitzenbergenLib.RitzenbergenLib.api("/bulitipp/maxspieltag.php"))
        .then((response) => response.text())
        .then((result)=> parseInt(result));
      }
    },
    paarungen: {
      get(){
        const params = new URLSearchParams({
          spieltag: this.maxspieltag
        });
        return fetch(RitzenbergenLib.RitzenbergenLib.api("/bulitipp/paarungen.php?"+params.toString()))
        .then((response) => response.json())
        .then((result2) => {
          if(result2.reload) this.update();
          return result2.data;
        })
        .then((result) => {
          return result.map(el => new RitzenbergenLib.Paarung(el[0],el[1],el[2]));
        })
        .catch((error) => {
          return null;
        });
      },
      watch: ["maxspieltag"],
      default: [new RitzenbergenLib.Paarung("Lade...","Lade..."),new RitzenbergenLib.Paarung("Lade...","Lade..."),new RitzenbergenLib.Paarung("Lade...","Lade..."),new RitzenbergenLib.Paarung("Lade...","Lade..."),new RitzenbergenLib.Paarung("Lade...","Lade..."),new RitzenbergenLib.Paarung("Lade...","Lade..."),new RitzenbergenLib.Paarung("Lade...","Lade..."),new RitzenbergenLib.Paarung("Lade...","Lade..."),new RitzenbergenLib.Paarung("Lade...","Lade...")]
    },
    ergebnisse: {
      get(){
        return fetch(RitzenbergenLib.RitzenbergenLib.api("/bulitipp/ergebnisse.php"))
        .then((response) => response.json())
        .then((result2) => {
          if(result2.reload) this.update();
          return result2.data;
        })
        .then((result) => {
          return result.map((el,i) => new RitzenbergenLib.Ergebnis(this.paarungen[i],el[0],el[1]));
        })

      },
      watch: ["paarungen"]
    },
    tipps: {
      get(){
        return fetch(RitzenbergenLib.RitzenbergenLib.api("/bulitipp/tipps.php?spieltag="+this.maxspieltag))
        .then((response) => response.json())
        .then(response => response.data);
      },
      watch: ["maxspieltag"],
      default: []
    },
    token: {
      get(){
        return fetch(RitzenbergenLib.RitzenbergenLib.api("/bulitipp/login.php?kuerzel="+this.kuerzel+"&password="+this.password))
        .then((response)=>response.text())
        .then((response)=>response=="Benutzer nicht gefunden"?null:response)
        .then((response)=>{
          if(response == "Falsches Passwort") {
            this.wrongpassword = true;
            return null;
          } else {
            this.wrongpassword = false;
            return response;
          }
        });
      },
      default: null,
      watch: ["kuerzel", "password"],

    }
  },
  computed: {
    sortedUsers() {
      if(this.users instanceof Array) return [...this.users].sort((a, b) => b.points - a.points);
    },

    loading(){
      return this.$asyncComputed.users.updating || this.$asyncComputed.ts.updating;
    },

  },
  methods: {
    gs(i) {
      let result = 0;
      this.spieltage[i].forEach((element) => {
        result += element;
      });
      return result;
    },
    update(){
      location.reload();
    },
    login(kuerzel, password){
      console.log("Login");
      this.kuerzel = kuerzel;
      this.password = password;
    },
    logout(){
      this.token=null;
      this.kuerzel = "";
      this.password = "";
      this.wrongpassword = false;
    },
		filterUsers(users){
				return users.filter((el)=>el.points>0&&this.maxspieltag>=2);
		}
  },
  data(){
    return {
      tippenoffen: false,
      debug: false,
      amtippen: false,
      kuerzel: "",
      password: "",
      wrongpassword: false
    }
  }
};
</script>
<template>
	<Loading v-show="loading && !debug" />
	<Navbar buttontext="Tippen" @clickbtn="tippenoffen = true" />
	<section
		class="header16 cid-u6k7q0xIhk bulitipp mbr-fullscreen mbr-parallax-background"
		id="hero-17-u6k7q0xIhk"
	>
		<div
			class="mbr-overlay"
			style="opacity: 0.3; background-color: rgb(0, 0, 0)"
		></div>
		<div class="container-fluid">
			<div class="row">
				<div class="content-wrap col-12 col-md-10">
					<h1
						class="mbr-section-title mbr-fonts-style mbr-white mb-4 display-1"
					>
						<strong>Willkommen im Bundesliga Tippspiel</strong>
					</h1>
					<p
						class="mbr-fonts-style mbr-text mbr-white mb-4 display-7"
					>
						Saison {{ saison }}/{{ saison + 1 }}
					</p>
					<br /><br />
				</div>
			</div>
		</div>
	</section>

	<Modal v-show="tippenoffen" @closemodal="tippenoffen = false">
		<Tippen v-show="token != null" :token="token" @logout="logout" />

		<TippenEinloggen
			v-show="token == null"
			@login="login"
			:wrongpassword="wrongpassword"
		/>
	</Modal>

	<Uebersicht
		:paarungen="paarungen"
		:tipps="tipps"
		:users="filterUsers(users)"
		:spieltag="maxspieltag"
	/>

	<!-- Rangliste -->

	<Rangliste
		:users="filterUsers(sortedUsers)"
		:spieltag="maxspieltag"
		:tipps="tipps"
		:results="ergebnisse"
	/>

	<!-- Paarungsergebnisse -->

	<Paarungsergebnisse :ergebnisse="ergebnisse" :maxspieltag="maxspieltag" :users="users" :tipps="tipps" />

	<!-- Punktetabelle -->
	<Tabelle :users="users" :ts="ts" />

	<br />
	<br />
	<br />

	<MyFooter />
</template>
<style scoped>
@import "../assets/css/bulitipp2.css";
#hero-17-u6k7q0xIhk {
	margin-bottom: 100px;
}
</style>
