import { Component, OnInit } from '@angular/core';
import { IArchive } from '@shared/models/archive.model';
import { ISettings } from '@shared/models/settings.model';
import { HelperService } from '@shared/services/helper.service';

@Component({
  selector: 'app-archives',
  templateUrl: './archives.component.html',
  styleUrls: ['./archives.component.scss']
})
export class ArchivesComponent implements OnInit {

  urlParams = new URLSearchParams(window.location.search);
  archives: IArchive[] = [];
  filteredArchives: IArchive[] = [];
  settings: ISettings = {} as ISettings;

  constructor(private helperService: HelperService) { }

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

  loadSettings(): void {
    this.helperService.getSettings().subscribe({
      next: (data: ISettings) => {
        this.settings = data;
      },
      complete: () => {
        this.loadArchive();
      }
    });
  }

  loadArchive(): void {
    this.helperService.getArchive().subscribe(data => {
      this.archives = data;
      this.filteredArchives = data;
    });
  }

  parseTimestamp(timestamp: string): string {
    return !!timestamp ? '(' + this.helperService.parseTimestamp(timestamp) + ')' : '';
  }

  searchArchive(arg: string, clear?: boolean): void {
    if (!!arg) {
      this.filteredArchives = this.archives.filter(entry => entry.postTitle.toLowerCase().includes(arg.toLowerCase()));
    } else {
      this.filteredArchives = this.archives;
    }

    if (clear) {
      (document.getElementById('search') as HTMLInputElement).value = '';
    }
  }
}
