import { Injectable } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
import { filter } from 'rxjs/operators';
import { MessageService } from 'primeng/api';
import { API } from '../services/api.service';
import { securityFunctions } from './security';

@Injectable({
    providedIn: 'root'
})
export class RouteChangeService {
    constructor(private router: Router, private apiService: API) {
        this.setupRouteChangeSubscription();
        // this.checkSessionMsg()
    }

    private setupRouteChangeSubscription() {
        this.router.events
            .pipe(filter(event => event instanceof NavigationEnd))
            .subscribe(() => {
                const currentUrl = this.router.url;
                // Check the current route's URL

                if (currentUrl.includes('Unauthorized') || currentUrl == '/' || currentUrl.includes('/404') || currentUrl.includes('/error') || currentUrl.includes('/Auth') || currentUrl.includes('/Home') || currentUrl.includes('/Login')) {
                    // console.log('Not making API call for 404 or error route:', currentUrl);
                } else {
                    let LoginUserData = JSON.parse(securityFunctions.getSessionStorage('LoginUserData'));
                    // Call your API function here
                    let url = currentUrl
                    if (currentUrl.includes('?')) {
                        url = currentUrl.split('?')[0]
                    }
                    let obj = {
                        "page_url": url,
                        "user_id": LoginUserData.user_id,
                        "project_id": '2405170833594899108'
                    }
                    this.apiService.AdminPost('/MenuMasterNew/IsAuthorizedPage', obj).subscribe(
                        (response) => {
                            if (!response.resp) {
                                this.router.navigate(['/Unauthorized']);
                            }
                        },
                        (error) => {
                            this.router.navigate(['/'])
                        }
                    );
                }
            });
    }
}