<template>
    <div>
        <manage-sidebar />
        <div class="page-wrapper">
            <div class="page-header d-print-none">
                <div class="container-fluid">
                    <div class="row g-2 align-items-center">
                        <div class="col">
                            <div class="page-pretitle">Manage</div>
                            <h2 class="page-title">Realtime Detection Logs (MQTT)</h2>
                        </div>
                        <div class="col-auto">
                            <button class="btn btn-primary" @click="refreshLogs" :disabled="loading">
                                <span v-if="loading">
                                    <i class="fa fa-spinner fa-spin me-2"></i> Refreshing...
                                </span>
                                <span v-else>
                                    <i class="fa fa-refresh me-2"></i> Refresh
                                </span>
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <div class="page-body">
                <div class="container-fluid">
                    <div class="card">
                        <div class="card-body">
                            <div v-if="loading" class="text-center my-5">
                                <i class="fa fa-spinner fa-spin fa-3x"></i>
                                <p class="mt-4">Loading data, please wait...</p>
                            </div>
                            <div v-else>
                                <div class="table-responsive">
                                    <table class="table table-hover table-borderd">
                                        <thead>
                                            <tr>
                                                <th>#</th>
                                                <th>Datetime (WIB)</th>
                                                <th>Label / Name / Subject</th>
                                                <!-- <th>Confidence</th> -->
                                                <th>Camera Number</th>
                                                <th>Camera Label</th>
                                                <th>Object Details</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <tr v-for="(log, index) in logs" :key="log.id">
                                                <td>{{ index + 1 }}</td>
                                                <td style="min-width: 160px;">{{ log.created_at }}</td>
                                                <td style="min-width: 250px;">{{ log.name }}</td>
                                                <!-- <td>
                                                    {{ log.confidence !== null ? log.confidence.toFixed(2) + "%" : "N/A" }}
                                                </td> -->
                                                <td>{{ log.camera }}</td>
                                                <td style="min-width: 400px;">{{ log.cameraLabel }}</td>
                                                <td style="min-width: 500px;">
                                                    {{ log.details }}
                                                </td>
                                            </tr>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <manage-footer />
        </div>
    </div>
</template>

<script>
import ManageSidebar from "@/views/manage/sidebar.vue";
import ManageFooter from "@/views/manage/footer.vue";
import mqttClient from "@/mqttClient";
import Swal from "sweetalert2";
import { mapGetters, mapActions } from 'vuex';
import axios from 'axios';

export default {
    name: "RealtimeDetection",
    components: { ManageSidebar, ManageFooter },
    data() {
        return {
            logs: [],
            loading: false,
            autoRefreshInterval: null,
        };
    },
    computed: {
        ...mapGetters(['user', 'authToken', 'refreshToken'])
    },
    methods: {
        ...mapActions(['logout', 'setAuthToken', 'setRefreshToken']),

        refreshLogs() {
            this.loading = true;
            mqttClient.end(true, () => {
                mqttClient.reconnect();
            });
        },
        startAutoRefresh() {
            this.autoRefreshInterval = setInterval(() => {
                if (this.logs.length > 50) { // Jika log melebihi 50 item
                    this.logs = this.logs.slice(0, 50); // Pertahankan hanya 50 item terbaru
                }
            }, 1000);
        },
        stopAutoRefresh() {
            clearInterval(this.autoRefreshInterval);
        },
        isJsonString(str) {
            try {
                JSON.parse(str);
                return true;
            } catch (e) {
                return false;
            }
        },
        async handleTokenRefresh() {
            try {
                const refreshToken = this.refreshToken; // Refresh token dari Vuex atau localStorage
                if (!refreshToken) throw new Error("No refresh token available");

                const response = await axios.post("/api/refresh-token", {
                    refresh_token: refreshToken,
                });

                const { token, refresh_token: newRefreshToken } = response.data;

                // Perbarui token di Vuex dan Axios
                this.setAuthToken(token);
                this.setRefreshToken(newRefreshToken);
                this.setAxiosDefaults(token);

                console.log("Token refreshed successfully.");
                return token;
            } catch (error) {
                console.error("Error refreshing token:", error);
                Swal.fire("Error", "Session expired. Please log in again.", "error");
                this.logout();
            }
        },
        setupAxiosInterceptors() {
            axios.interceptors.response.use(
                (response) => response,
                async (error) => {
                    const { config, response } = error;
                    if (response && response.status === 401 && !config._retry) {
                        config._retry = true;
                        const newToken = await this.handleTokenRefresh();
                        if (newToken) {
                            config.headers["Authorization"] = `Bearer ${newToken}`;
                            return axios(config);
                        }
                    }
                    return Promise.reject(error);
                }
            );
        },
        logout() {
            this.$store.dispatch("logout");
            this.clearSession();
        },
        clearSession() {
            sessionStorage.removeItem("authToken");
            sessionStorage.removeItem("refreshToken");
            sessionStorage.removeItem("user");
            localStorage.removeItem("authToken");
            localStorage.removeItem("refreshToken");
            localStorage.removeItem("user");
        },
        setAxiosDefaults(token) {
            axios.defaults.headers.common["Authorization"] = `Bearer ${token}`;
        },
        showErrorAlert(message) {
            Swal.fire({
                icon: 'error',
                title: message,
                toast: true,
                position: 'top-end',
                showConfirmButton: false,
                timer: 3000,
            });
        },

    },
    mounted() {
        this.startAutoRefresh();

        if (!this.user || !this.authToken) {
            Swal.fire({
                icon: 'error',
                title: 'Error',
                text: 'You do not have access. Please log in first.',
                toast: true,
                position: 'top-end',
                showConfirmButton: false,
                timer: 3000
            }).then(() => {
                this.logout();
            });
        } else {

            mqttClient.on('message', (topic, message) => {
                const messageStr = message.toString();
                if (!this.isJsonString(messageStr)) {
                    console.warn(`Invalid JSON message: ${messageStr}`);
                    return;
                }

                try {
                    const payload = JSON.parse(messageStr);
                    const topicRegex = /^viseron\/binary_sensor\/camera_(\d+)_object_detected\/state$/;
                    const match = topic.match(topicRegex);

                    if (match) {
                        const cameraNumber = match[1];
                        const objectsDetected = payload.attributes.objects.map(obj => ({
                            created_at: new Date().toLocaleString("id-ID", { timeZone: 'Asia/Jakarta' }),
                            name: obj.label,
                            camera: `Camera ${cameraNumber}`,
                            cameraLabel: payload.attributes.name,
                            confidence: obj.confidence * 100,
                            details: `Width: ${obj.rel_width}, Height: ${obj.rel_height}, X1: ${obj.rel_x1}, Y1: ${obj.rel_y1}, X2: ${obj.rel_x2}, Y2: ${obj.rel_y2}`
                        }));

                        this.logs = [...objectsDetected, ...this.logs.slice(0, 49)];
                    }
                } catch (error) {
                    console.error('Failed to parse message as JSON:', error);
                }
            });
        }
        this.setupAxiosInterceptors();

    },
    beforeDestroy() {
        this.stopAutoRefresh();
    }
};
</script>

<style scoped>
.table {
    margin-top: 20px;
}

.text-center {
    margin-top: 20px;
}

.fa-spinner {
    color: #007bff;
}
</style>
