import { Component, EventEmitter, Input, Output, OnDestroy, ViewChild, AfterViewInit, ElementRef, AfterViewChecked } from '@angular/core';
import { ScrollEventData, ScrollView } from '@nativescript/core/ui/scroll-view';
import { ActionBarScrollSyncService } from '~/core/services/action-bar-scroll-sync.service';
import { Subscription } from 'rxjs';
import { SortSearchTag, ModalType } from '~/pages/event/types/common.types';

@Component({
    selector: 'SearchSortTags',
    moduleId: module.id,
    templateUrl: './search-sort-tags.component.html',
})
export class SearchSortTagsComponent implements OnDestroy, AfterViewInit, AfterViewChecked {
    @Output() openSearchModal = new EventEmitter();
    @Output() openSortingModal = new EventEmitter();
    @Input() tags: SortSearchTag[];

    @ViewChild('scrollV', { static: true })
    scrollview: ElementRef
    sub: Subscription;
    constructor(
        private scrollService: ActionBarScrollSyncService,
    ) {
    }
    offset: number;
    ngAfterViewChecked(): void {
        const sv = this.scrollview.nativeElement as ScrollView
        if (sv.scrollableWidth > 0 && sv.horizontalOffset != this.offset) {
            sv.scrollToHorizontalOffset(this.offset, false);
        }
    }
    ngOnDestroy(): void {
        this.scrollService.resetCount()
        this.sub.unsubscribe();
    }

    ngAfterViewInit(): void {
        this.sub = this.scrollService.currentScrollState.subscribe(res => {
            this.offset = res.value;
            this.scrollview.nativeElement.scrollToHorizontalOffset(res.value, false);
        })
    }

    onScroll(args: ScrollEventData) {
        this.scrollService.changeScroll(args.scrollX)
    }
    onClick(modalType: ModalType) {
        if (modalType === ModalType.Search) {
            this.openSearchModal.emit()

        } else if (modalType === ModalType.Sort) {
            this.openSortingModal.emit()
        }
    }

}