<template>
    <dartPickerComponent @sendFields="handleFields"/>

    <img
        v-for="(dart, index) in darts"
        :key="index"
        src = "~assets//dart.svg" 
        class = "dart" 
        :style="{ 
            top: dart.top + 'px', 
            left: dart.left + 'px'
        }"
    />

    <div class="q-pa-md flex flex-center">
        <q-card
            class="q-pa-lg shadow-3"
            style="width: 100vw; padding: 25px;"
        >   
            <q-card-section>
                <div v-if="gameIsLocal" class="text-h6 q-mt-md">Local Game</div>
                <div v-if="!gameIsLocal" class="text-h6 q-mt-md">Online Game</div>

                <div class="text-subtitle2 text-black">
                    Current player: {{ courentPlayer.username }}
                </div>
            </q-card-section>

            <q-separator />

            <q-card-section v-if="courentPlayer.id != user.id && !gameIsLocal" class="flex flex-center">
                <div class="text-h1">Waiting for Player...</div>
            </q-card-section>

            <q-card-section v-if="courentPlayer.id == user.id || gameIsLocal" >
                <div class = "dartBoardDiv" v-touch-pan.prevent.mouse = "onPan">
                    <div class="text-h5 text-black">{{ gamePoints }}</div>

                    <div class="text-h6 text-black">{{ selected.name ?? "0" }}</div>

                    <img id = "dartBoard" class = "dartBoard" src = "~assets/dartBoard.svg" />
                </div>

                <div v-if="courentDart != 3" class="row justify-center q-gutter-md q-pa-lg">
                    <q-btn
                        label="Set!"
                        color="primary"
                        @click="set"
                        rounded
                        unelevated
                        size="lg"
                        class="full-width"
                        style="max-width: 20vw;"
                    />
                    <br>
                    <q-btn
                        label="Skip"
                        color="primary"
                        @click="skip"
                        rounded
                        unelevated
                        size="lg"
                        class="full-width"
                        style="max-width: 20svw;"
                    />
                </div>
            </q-card-section>

            <q-card-actions v-if="courentDart == 3 && courentPlayer.id == user.id || courentDart == 3 && gameIsLocal" align="center">
              <q-btn
                    label="Submit!"
                    color="primary"
                    @click="submit"
                    rounded
                    unelevated
                    size="lg"
                    class="full-width"
                    style="max-width: 50vw;"
              />
            </q-card-actions>
        </q-card>
    </div>
</template>

<script setup>
import dartPickerComponent from "./Components/dartPickerComponent.vue"
import { ref, onMounted, onUnmounted  } from "vue";
import { useQuasar, LocalStorage } from 'quasar'
import { useRouter } from 'vue-router'
import { api } from 'src/boot/axios';

const router = useRouter()
const $q = useQuasar();

const user = ref({ username:"", id:0 });
const gameID = ref(null);
const gameIsLocal = ref(null);

const courentDart = ref(0)
const darts = ref([
    { top: null, left: null, points: null },
    { top: null, left: null, points: null },
    { top: null, left: null, points: null }
])

const courentPlayer = ref({ username:null, id:null })
const gamePoints = ref(null)
const turnOrder = ref(null)

const posRelative = ref({ top: null, left: null })
const distanceFromCenter = ref(null)
const dartRing = ref(null)
const degrees = ref(null)
const field = ref(null)
const selected = ref({ id: null, name: null, points: null })
const fields = ref({})

var canUpdate = false

const storedUser = LocalStorage.getItem("user")
if (storedUser) {
    user.value = storedUser
} else {
    router.push("/user/username")
}

const storedgameID = LocalStorage.getItem("gameID")
if (storedgameID) {
    gameID.value = storedgameID

    api.get(`/api/games/${gameID.value}`)

    .then(function (response) {
        
        gameIsLocal.value = response.data.is_local
        courentPlayer.value.id = response.data.current_playing_user
        updateCourentPlayerUsername()
        turnOrder.value = response.data.turn_order

        gamePoints.value = response.data.players.find(
            player => player.id === courentPlayer.value.id
        )?.points || 0


        canUpdate = true
    })

    .catch(function (error) {
        console.log(error);

        $q.notify({
            type: "negative",
            message: error.response.data.error,
        });
    });
} else {
    router.push("/")
}

async function update() {
    if (!canUpdate) {return}

    api.get(`/api/games/${gameID.value}`)

    .then(function (response) {
        
        courentPlayer.value.id = response.data.current_playing_user
        gamePoints.value = response.data.players.find(
            player => player.id === courentPlayer.value.id
        )?.points || 0

        updateCourentPlayerUsername()
    })

    .catch(function (error) {
        console.log(error);

        $q.notify({
            type: "negative",
            message: error.response.data.error,
        });
    });
}

async function updateCourentPlayerUsername() {
    api.get(`/api/users/${courentPlayer.value.id}`)

    .then(function (response) {
        
        courentPlayer.value.username = response.data.username
    })

    .catch(function (error) {
        console.log(error);

        $q.notify({
            type: "negative",
            message: error.response.data.error,
        });
    });
}

function distanceBetween(x1, y1, x2, y2) {
  const dx = x2 - x1;
  const dy = y2 - y1;
  
  return Math.sqrt(dx * dx + dy * dy);
}

function degreesBetweenPoints(x1, y1, x2, y2) {
  let degrees = Math.atan2(y2 - y1, x2 - x1) * (180 / Math.PI)
  degrees = degrees - 90 + 18/2
  if (degrees < 0) degrees += 360
  return degrees
  // Damit ich nicht vergesse woher die zahlen kommen 😅:
  // 90 da sonst die 0° rechts währe
  // 18 da 360° / 20 (Dart hat 20 felder rund um wehn ich zhälen kann)
  // /2 da um ein halbes feld zurück zu gehen da ich zu fauel bin das später mit einzurechen :D
}

function onPan({ position, isFinal }) {
    if (courentDart.value > 2) {
        return
    }

    const offset = -50;

    darts.value[courentDart.value].top = position.top + offset
    darts.value[courentDart.value].left = position.left

    
    const dartBoard = document.getElementById('dartBoard')
    const dartRect = dartBoard.getBoundingClientRect()

    const centerTop = dartRect.top + dartRect.height / 2
    const centerLeft = dartRect.left + dartRect.width / 2

    posRelative.value.top = Math.round(position.top - centerTop + offset)
    posRelative.value.left = Math.round(position.left - centerLeft)

    const distance = distanceBetween(darts.value[courentDart.value].left, darts.value[courentDart.value].top, centerLeft, centerTop)
    degrees.value = degreesBetweenPoints(darts.value[courentDart.value].left, darts.value[courentDart.value].top, centerLeft, centerTop)
    field.value = Math.floor(degrees.value/18)

    if (distance < dartRect.height / 2) {
        distanceFromCenter.value = distance
        var id

        // ich muss noch die richtigen werte aus der svg ausrechnen :C
        if (distance < dartRect.height / 45) {
            dartRing.value = 0
            id = String(0)

        } else if (distance < dartRect.height / 20) {
            dartRing.value = 1
            id = String(1)

        } else if (distance < dartRect.height / 3.5) {
            dartRing.value = 2
            id = String(1)
            if (field.value < 10) id = id + String(0)
            id = id + String(field.value)

        } else if (distance < dartRect.height / 3.2) {
            dartRing.value = 3
            id = String(2)
            if (field.value < 10) id = id + String(0)
            id = id + String(field.value)

        } else if (distance < dartRect.height / 2.16) {
            dartRing.value = 4
            id = String(3)
            if (field.value < 10) id = id + String(0)
            id = id + String(field.value)

        } else if (distance < dartRect.height) {
            dartRing.value = 5
            id = String(4)
            if (field.value < 10) id = id + String(0)
            id = id + String(field.value)

        }

        selected.value.id = id
        selected.value.name = fields.value[Number(id)].name
        selected.value.points = fields.value[Number(id)].points

    } else {
        distanceFromCenter.value = null
        dartRing.value = null
    }

    if (isFinal) {
        console.log("end")
    }
}

function set() {
    if (courentDart.value <= 2) {
        darts.value[courentDart.value].points = selected.value.points
        courentDart.value += 1
    }
}

function skip() {
    if (courentDart.value <= 2) {
        darts.value[courentDart.value].left = -100
        darts.value[courentDart.value].top = -100
        courentDart.value += 1
    }
}

async function submit() {
    
    api.post(`/api/games/${gameID.value}/turns`, {
        "user": courentPlayer.value.id,
        "first_throw": darts.value[0].points ?? 0,
        "second_throw": darts.value[1].points ?? 0,
        "third_throw": darts.value[2].points ?? 0,
    })
    
    .then(function () {
        
        $q.notify({
            type: "positive",
            message: "Success!",
        });

        darts.value[0].top = 0; darts.value[0].left = 0; darts.value[0].points = null
        darts.value[1].top = 0; darts.value[1].left = 0; darts.value[1].points = null
        darts.value[2].top = 0; darts.value[2].left = 0; darts.value[2].points = null

        courentDart.value = 0
    })
    
    .catch(function (error) {
        console.log(error);

        $q.notify({
            type: "negative",
            message: error.response.data.error,
        });
    });
}

const handleFields = (data) => {
  fields.value = data
}

let intervalId = null

onMounted(() => {
    update()

    intervalId = setInterval(update, 1000)
})

onUnmounted(() => {
    clearInterval(intervalId)
})
</script>
