import { Injectable } from '@angular/core';
import { Post } from '../model/post';

import { Observable } from 'rxjs/Observable';
import { HttpClient, HttpHeaders } from '@angular/common/http';

import 'rxjs/add/operator/map';
import 'rxjs/add/observable/of';

@Injectable()
export class DataloaderService {

  constructor(private http: HttpClient) { }

  getPosts(): Observable<Post[]> {
    return this.http.get('assets/posts.json').map(posts => {
      const res: Post[] = [];
      // fill it up
      for (const index in posts) {
          const post: any = posts[index];
          // console.log(post);
          const temp: Post = new Post(post.id);
          temp.title = post.info.title;
          temp.type = post.type;
          temp.tags = post.info.tags;
          temp.languages = post.info.languages;
          // console.log('got this timestamp: ' + post.info.created_timestamp);
          temp.created_timestamp = new Date(post.info.created_timestamp * 1000);
          // console.log('converted it to this: ' + temp.created_timestamp);
          res.push(temp);
      }
      // console.log('these are the posts...');
      // console.log(res);
      return res;
    });
  }

  /**
   * Fetch the 'full fat' post. This returns HTML content that can be wrapped in any container, no sanitizing done.
   * @param filename the filename for which the post needs to be fetched
   */
  getFullHtml(post: Post, language: string): Observable<String> {
    const httpOptions = {
      headers: new HttpHeaders({ 'Content-Type': 'text/html', 'Accept': 'text/html' })
    };

    // check if the post actually has a filename for the 'full version' and the post is translated to the given language
    if (post.languages === undefined) {
      console.log(`post with id ${post.id} has no languages defined...`);
      return Observable.of('You encounter a pirate without a tongue. Curious.');
    }
    if (post.languages.indexOf(language) !== -1) {
      // language is defined!
      const url = `assets/post/${post.id}/full-${language}.html`;
      return this.http.get(url, {responseType: 'text'});
    } else {
      return Observable.of('You encounter a pirate without a tongue. Curious.');
    }

  }

}
