<script setup>
    import { onMounted, ref } from 'vue';
    import { useRoute } from 'vue-router';
    import Spiner from '../components/ui/Spiner.vue';
    import CardLoad from '../components/CardLoad.vue';
    import useDirectionsRender from '../composables/useDirectionRender';
    import { GoogleMap, Marker, CustomMarker, Polyline } from 'vue3-google-map';
    import CardEmpty from '../components/CardEmpty.vue';
    import useTrackingLoad from '../composables/useTrackingLoad';
    import { useI18n } from 'vue-i18n';

    const mapKey = import.meta.env.VITE_MAP_KEY;

    const { getDirections } = useDirectionsRender()
    const { getLoadTracking, load, loading } = useTrackingLoad();
    const route = useRoute();
    const zoom = ref(6);
    const heightMap = ref(768);
    const vehicleLastLocation = ref(null);
    const originCoords = ref(null);
    const destinationCoords = ref(null);
    const polylines = ref([]);
    const isLoadActive = ref(false);
    const windowWidth = ref(window.innerWidth);

    onMounted(() => {
        window.addEventListener('resize', handleResize);
        if(window.innerWidth <= 1024) {
            zoom.value = 4;
            heightMap.value = 420;
        }
        initData();
    });

    const { t } = useI18n();
    const initData = async() => {
        const id = route.params['code'];
        await getLoadTracking(id)
        if(load.value !== null) {
            // console.log(load.value)
            const addressOrigin = load.value?.origin_geo?.coordinates;
            const addressDestination = load.value?.destination_geo?.coordinates;
            if(addressOrigin && addressDestination) {
                originCoords.value = {lat: Number.parseFloat(addressOrigin[0]), lng: Number.parseFloat(addressOrigin[1])};
                destinationCoords.value = {lat: Number.parseFloat(addressDestination[0]), lng: Number.parseFloat(addressDestination[1])};

                polylines.value = await getDirections(originCoords.value, destinationCoords.value);

            }
            
            if(load.value.vehicle) {
                vehicleLastLocation.value = {
                    lat: parseFloat(load.value.vehicle.last_location_lat),
                    lng: parseFloat(load.value.vehicle.last_location_lng)
                }
                console.log(vehicleLastLocation);
            }


            console.log(load.value);
            switch (load.value.load_status) {
                case 'Loading':
                    isLoadActive.value = true;
                    break;
                case 'Transit':
                    isLoadActive.value = true;
                    break;
                case 'Downloading':
                    isLoadActive.value = true;
                    break;
            
                default:
                    isLoadActive.value = false;
                    break;
            }

        }
    }

    const handleResize = () => {
        windowWidth.value = window.innerWidth
        if(windowWidth.value <= 1024){
            zoom.value = 4
            heightMap.value = 420;
        } else {
            zoom.value = 6;
            heightMap.value = 768;
        }
    }
</script>

<template>
    <h2 class="title text-center mt-5">{{ t('loads.trackingLoad') }}</h2>
    <Spiner v-if="loading"/>
    <div v-else>
        <div v-if="load">
            <CardLoad :load="load" :read-only="true"/>
            <br/>
            <GoogleMap
                    :api-key="mapKey"
                    :center="{lat:19.432600, lng:-99.133209}"
                    :zoom="zoom" 
                    :min-zoom="2"
                    :max-zoom="20"
                    :style="{width: 100 + '%', height: heightMap + 'px'}"
                    :options="{
                        zoomControl: true,
                        mapTypeControl: true,
                        scaleControl: true,
                        streetViewControl: true,
                        rotateControl: true,
                        fullscreenControl: true
                    }"
                > 
                    <Marker v-if="originCoords" :options="{position: originCoords, label: 'O', title: 'Destino'}" />
                    <Marker v-if="destinationCoords" :options="{position: destinationCoords, label: 'D', title: 'Origen'}" />
                    <CustomMarker
                        v-if="vehicleLastLocation && load.vehicle.background_tracking && isLoadActive"
                        :options="{position: vehicleLastLocation}"
                        :clickable="false"
                        :draggable="false"
                        >
                        <div style="text-align: center">
                            <!-- <img src="/images/freeTruck.png" width="25" height="25" /> -->
                            <i class="fa-solid fa-truck" :style="{fontSize: 25 + 'px', color: 'green'}"></i>
                        </div>
                    </CustomMarker>
                    <Polyline 
                        v-if="polylines"
                        :options="{
                            path: polylines,
                            // geodesic: true,
                            strokeColor: '#2D90BB',
                            strokeOpacity: 0.7,
                            strokeWeight: 5,
                            clickable: true,
                            fillColor: '#75ad3e',
                        }" 
                    />
                </GoogleMap>
        </div>
        <CardEmpty v-else :text="t('loads.noInfo')"/>
    </div>
</template>

<style scoped>

</style>