import { Component, EventEmitter, OnInit, Output } from '@angular/core';
import { ActivatedRoute, UrlSegment } from '@angular/router';

@Component({
    selector: 'same-url-navigation-detector',
    template: '<ng-container></ng-container>',
})
export class SameUrlNavigationDetectorComponent implements OnInit {
    private segments: UrlSegment[] = [];

    @Output() sameUrlNavigation = new EventEmitter<void>();

    constructor(protected route: ActivatedRoute) {}

    ngOnInit(): void {
        this.observeSameUrlNavigation();
    }

    private observeSameUrlNavigation() {
        this.route.url.subscribe({
            next: (segments) => {
                if (this.areSegmentsEqual(segments)) {
                    this.sameUrlNavigation.emit();
                }

                this.segments = segments;
            },
        });
    }

    private areSegmentsEqual(newSegments: UrlSegment[]) {
        if (this.segments.length !== newSegments.length) {
            return false;
        }

        return this.segments.every((segment, index) => {
            return segment.path === newSegments[index].path;
        });
    }
}
