<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">Live CCTV Feeds (Internet)</h2>
                        </div>
                    </div>
                </div>
            </div>

            <div class="page-body" style="min-height: 79vh">
                <div class="container-fluid">
                    <div class="row row-deck row-cards">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-body">
                                    <div class="d-flex justify-content-between">
                                        <span class="text-danger fst-italic">
                                            Click pada gambar untuk fullscreen!
                                        </span>
                                        <button class="btn btn-primary ms-3" @click="fetchCCTVStreams">
                                            <i class="fa fa-refresh me-1"></i> Refresh
                                        </button>
                                    </div>
                                    <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 class="row mt-3">
                                        <div v-for="(stream, index) in cctvStreams" :key="index"
                                            class="col-md-6 col-lg-3 mb-4">
                                            <div class="card shadow h-100">
                                                <div class="card-header p-2 pb-1">
                                                    <strong>
                                                        {{ stream.camera_name }} ({{ stream.resolution }})
                                                    </strong>
                                                </div>
                                                <div class="card-body p-0 position-relative">
                                                    <img :src="stream.ip_address" class="img-fluid" alt="CCTV Stream"
                                                        @click="goFullScreen($event)" @load="handleImageLoad(index)"
                                                        @error="handleImageError(index)">
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <manage-footer />
    </div>
</template>

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

export default {
    name: 'CCTVStreams',
    components: {
        ManageSidebar,
        ManageFooter
    },
    data() {
        return {
            cctvStreams: [],
            loading: false,
            loadingImages: []
        };
    },
    computed: {
        ...mapGetters(['user', 'authToken', 'refreshToken'])
    },
    methods: {
        ...mapActions(['logout', 'setAuthToken', 'setRefreshToken']),
        fetchCCTVStreams() {
            this.loading = true;
            axios.post('/api/cctv/internet')
                .then(response => {
                    this.cctvStreams = response.data || [];
                    // Initialize loading states for each image
                    this.loadingImages = Array(this.cctvStreams.length).fill(true);
                })
                .catch(error => {
                    console.error('Error fetching CCTV streams:', error);
                    if (error.response && error.response.status === 401) {
                        this.handleTokenRefresh();
                    }
                })
                .finally(() => {
                    this.loading = false;
                });
        },
        goFullScreen(event) {
            const img = event.target;

            // Check if we are currently in fullscreen mode
            if (!document.fullscreenElement && // alternative standard method
                !document.mozFullScreenElement && !document.webkitFullscreenElement && !document.msFullscreenElement) { // current working methods
                if (img.requestFullscreen) {
                    img.requestFullscreen();
                } else if (img.webkitRequestFullscreen) {
                    img.webkitRequestFullscreen();
                } else if (img.msRequestFullscreen) {
                    img.msRequestFullscreen();
                }
            } else {
                if (document.exitFullscreen) {
                    document.exitFullscreen();
                } else if (document.webkitExitFullscreen) {
                    document.webkitExitFullscreen();
                } else if (document.msExitFullscreen) {
                    document.msExitFullscreen();
                }
            }
        },
        handleImageLoad(index) {
            this.loadingImages[index] = false;
        },
        handleImageError(index) {
            console.error(`Image failed to load for index ${index}`);
            this.loadingImages[index] = false;
        },
        async handleTokenRefresh() {
            try {
                const refresh_token = this.refreshToken;
                if (!refresh_token) throw new Error('No refresh token available');
                const response = await axios.post('/api/refresh-token', { token: refresh_token });
                const { token, refresh_token: new_refresh_token } = response.data;
                this.setAuthToken(token);
                this.setRefreshToken(new_refresh_token);
                this.setAxiosDefaults(token);
                return token;
            } catch (error) {
                Swal.fire('Error', 'Sesi anda telah habis, silahkan login ulang !', 'error');
                await this.logout();
            }
        },
        setupAxiosInterceptors() {
            axios.interceptors.response.use(
                response => response,
                async error => {
                    const { config, response: { status } } = error;
                    if (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);
                }
            );
        },
        clearSession() {
            sessionStorage.clear();
            localStorage.clear();
        },
        setAxiosDefaults(token) {
            axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
        },
        showSuccessAlert(message) {
            this.$swal.fire({
                icon: 'success',
                title: message,
                toast: true,
                position: 'top-end',
                showConfirmButton: false,
                timer: 3000
            });
        },
        showErrorAlert(message) {
            this.$swal.fire({
                icon: 'error',
                title: message,
                toast: true,
                position: 'top-end',
                showConfirmButton: false,
                timer: 3000
            });
        },
    },
    mounted() {
        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 {
            this.fetchCCTVStreams();
        }
        this.setupAxiosInterceptors();
    }
};
</script>

<style scoped>
.img-fluid {
    width: 100%;
    height: auto;
    cursor: pointer;
}

.image-loading-overlay {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(255, 255, 255, 0.7);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 1;
}

.image-loading-overlay .fa-spinner {
    font-size: 2rem;
    color: #007bff;
}
</style>
