import {Component, OnInit, Input, ViewChild, ElementRef} from '@angular/core';
import { Post } from 'app/model/post';
import { DataloaderService } from 'app/services/dataloader.service';
import {StateService} from '../../services/state.service';

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

  @Input() post: Post;

  /**
   * If this is set to true, the post component can reconfigure itself to display a short version. If false, it just shows the full version.
   */
  @Input() canBeShort: boolean;

  @ViewChild('htmlcontainer')
  htmlContainer: ElementRef;

  /**
   * A variable that indicates whether the component is displaying a short or long version.
   * @type {boolean}
   */
  shortVersion = false;

  /**
   * Construct the PostComponent.
   *
   * @param {DataloaderService} dataloaderService
   * @param {StateService} stateService
   */
  constructor(private dataloaderService: DataloaderService, private stateService: StateService) { }

  ngOnInit() {
    // TODO load the relevant HTML file!
    // console.log('post component has inited: '+this.post.id);
    // console.log(this.post);

    // console.log('PostComponent is loading: '+this.post.id);
    // console.log(this.post);

    this.dataloaderService.getFullHtml(this.post, this.stateService.getLanguage()).subscribe(content => {
      // console.log('PostComponent got content for '+this.post.id);
      // this is not the cause of the memory leak:\
      this.setContent(content);
    });

    this.stateService.getLanguageObservable().subscribe(language => {
      // change the content: language has been updated
      this.dataloaderService.getFullHtml(this.post, language).subscribe(content => {
        this.setContent(content);
      });
    });

    console.log('PostComponent.ngOnInit is done.');
  }

  /**
   * Set the content in a clever way: if the post component is set to a short version, this can fix that up.
   * @param {String} content
   */
  private setContent(content:String) {
    if(this.canBeShort) {
      const split = content.split("<splitter/>");
      if(split.length==2) {
        //only show the first one
        this.htmlContainer.nativeElement.innerHTML = split[0];
        this.shortVersion = true;
      } else {
        this.htmlContainer.nativeElement.innerHTML = content;
        this.shortVersion = false;
      }
    } else {
      this.htmlContainer.nativeElement.innerHTML = content;
      this.shortVersion = false;
    }
  }

  isActiveTag(tag: string): boolean {
    return this.stateService.isActiveTag(tag);
  }

  getPostTitle() {
   return this.post.title[this.stateService.getLanguage()];
  }
}
