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

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

  contents: PostModel[] = [];
  archives: IArchive[] = [];
  settings: ISettings = {} as ISettings;
  postsLoaded = 0;

  showdownmd: any;

  constructor(public helperService: HelperService) {
  }

  ngOnInit(): void {
    this.showdownmd = new showdown.Converter();

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

  loadArchive(): void {
    this.helperService.getArchive().subscribe({
      next: (data: IArchive[]) => {
        this.archives = data;
        this.settings.maxPosts = this.archives.length < this.settings.maxPosts ? this.archives.length : this.settings.maxPosts;
      },
      complete: () => {
        this.loadPosts();
      }
    });
  }

  loadPosts(): void {
    if (this.postsLoaded < this.settings.maxPosts) {
      this.helperService.getPost('./assets/posts/' + this.archives[this.postsLoaded].filename + '.json').subscribe({
        next: (data: PostModel) => {
          this.contents.push(data);
        },
        complete: () => {
          this.continue();
        },
        error: error => {
          this.continue(error);
        }
      });
    }
  }

  continue(error?: any): void {
    if (error) {
      const errorPost = new PostModel();
      errorPost.postTitle = 'Aw shucks!';
      errorPost.postContent = 'We couldn\'t load this post! Sorry! <strong>(' + error.status + ' ' + error.statusText + ')</strong>';
      errorPost.filename = 'not-found';
      this.contents.push(errorPost);
    }

    this.postsLoaded += 1;
    this.loadPosts();
  }

  generateHTML(markdown: string): void {
    return this.showdownmd.makeHtml(markdown);
  }
}
