import { Component, OnInit, OnDestroy, Input, inject } from '@angular/core';
import { NgClass } from '@angular/common';
import { RouterLink } from '@angular/router';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { Observable, Subscription } from 'rxjs';

import { Errors, Jump, JumpList, JumpListConfig } from '@models';
import { JumpsService } from '@services';
import { JumpPreviewComponent } from './jump-preview.component';

@Component({
    selector: 'app-jump-list',
    templateUrl: './jump-list.component.html',
    imports: [NgClass, MatProgressSpinnerModule, MatButtonModule, RouterLink, MatIconModule, JumpPreviewComponent],
})
export class JumpListComponent implements OnInit, OnDestroy {
    private jumpsService = inject(JumpsService);

    private _jumps: Subscription = new Subscription();
    errors: Errors = { errors: {} };
    query!: JumpListConfig;
    jumps: Array<Jump> = [];
    jumpsCount = 0;
    loading = false;
    currentPage = 1;
    pages: Array<number> = [1];
    lastUpdate: Date = new Date();

    @Input() limit = 0;
    @Input() refresh = 30000;
    @Input() title = '';
    @Input() showAdd = false;
    @Input() isUser = false;
    @Input() showMeta = false;
    @Input()
    set config(config: JumpListConfig) {
        if (config) {
            this.query = config;
            this.currentPage = 1;
            this.loading = true;
        }
    }

    ngOnInit() {
        this.runQuery();
    }

    ngOnDestroy() {
        this._jumps.unsubscribe();
    }

    setPageTo(pageNumber: number) {
        this.currentPage = pageNumber;
        this.runQuery();
    }

    runQuery() {
        if (this.limit) {
            this.query.filters.limit = this.limit;
            this.query.filters.offset = this.limit * (this.currentPage - 1);
        }

        const jumps$: Observable<JumpList> = this.jumpsService.query(this.query);
        this._jumps = jumps$.subscribe({
            next: (data: JumpList) => {
                this.loading = false;
                this.jumps = data.jumps;
                this.jumpsCount = data.jumpsCount;
                if (this.limit) {
                    this.pages = this.getTotalPages(this.jumpsCount, this.limit);
                }
            },
            error: (err) => {
                this.errors = err;
            },
        });
    }

    getTotalPages(count: number, limit: number) {
        // Used from http://www.jstips.co/en/create-range-0...n-easily-using-one-line/
        return Array.from(new Array(Math.ceil(count / limit)), (val, index) => index + 1);
    }
}
