<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">Person 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: 220px;">{{ 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";

export default {
    name: "PersonDetectionLogs",
    components: { ManageSidebar, ManageFooter },
    data() {
        return {
            logs: [],
            loading: false,
            autoRefreshInterval: null,
        };
    },
    methods: {
        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);
        },
    },
    mounted() {
        this.startAutoRefresh();

        mqttClient.on('message', (topic, message) => {
            try {
                const payload = JSON.parse(message.toString());
                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
                        .filter(obj => obj.label.toLowerCase() !== "person" && obj.label.toLowerCase() !== "person undetected" && obj.label.toLowerCase() !== "vehicle")
                        .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);
            }
        });
    },
    beforeDestroy() {
        this.stopAutoRefresh();
    },

};
</script>

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

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

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