import { Component, OnInit } from '@angular/core';
import { Title } from '@angular/platform-browser';
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-posts',
  templateUrl: './posts.component.html',
  styleUrls: ['./posts.component.scss']
})
export class PostsComponent implements OnInit {

  urlParams = new URLSearchParams(window.location.search);
  content: PostModel = new PostModel();
  settings: ISettings = {} as ISettings;

  showdownmd: any;

  constructor(private titleService: Title, private helperService: HelperService) {
  }

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

    this.helperService.getSettings().subscribe({
      next: (data: ISettings) => {
        this.settings = data;
      },
      complete: () => {
        if (this.urlParams.get('post')) {
          this.loadPost();
        }
      }
    });
  }

  loadPost(): void {
    this.helperService.getPost('./assets/posts/' + this.urlParams.get('post') + '.json').subscribe({
      next: (data: PostModel) => {
        this.content = data;
        this.content.timestamp = !!this.content.timestamp ? this.helperService.parseTimestamp(data.timestamp) : '';
        this.content.editedTimestamp = !!this.content.editedTimestamp ? this.helperService.parseTimestamp(data.editedTimestamp) : '';
        this.titleService.setTitle(this.content.postTitle + ' ~ ' + this.settings.blogTitle);
      },
      error: (error) => {
        this.content.postTitle = 'Whoops!';
        this.content.postContent = 'We couldn\'t load this post! <strong>(' + error.status + ')</strong>';
      }
    });
  }

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