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

import 'rxjs/add/operator/map';
import 'rxjs/add/operator/merge';
import 'rxjs/add/operator/concatMap';
import 'rxjs/add/observable/from';
import 'rxjs/add/operator/distinct';

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

  allPosts: Post[];
  filteredPosts:  Post[];
  tags = new Array<string>();

  constructor(private dataloaderService: DataloaderService, private stateService: StateService) {
  }

  ngOnDestroy(): void {
    // console.log('PostsComponent.ngOnDestroy called');

  }

  ngOnInit() {
    // console.log('PostsComponent ngOnInit()');
    // fetch the posts
    const posts2 = this.dataloaderService.getPosts();
    posts2.subscribe(p => {
      this.allPosts = p;

      //figure out the different tags so we can filter on them
      const temptags = new Array<string>();
      this.allPosts.forEach(p => p.tags.forEach(t => temptags.push(t)));
      console.log(temptags);
      //copy the temptags into the tags array, don't include duplicates
      temptags.forEach(tt => {
        if (this.tags.indexOf(tt) == -1) {
          this.tags.push(tt)
        }
      });
      //sort the array
      this.tags.sort((a, b) => a.localeCompare(b));

      //do the first filtered update!
      this.updateFilteredPosts(this.stateService.getLanguage());
    });
    console.log('PostsComponent ngOnInit() is done');

    //we start listening to language changes
    this.stateService.getLanguageObservable().subscribe(language => {
      console.log('posts component needs to switch languages!');
      this.updateFilteredPosts(language);
    });

  }

  filterOnType(type: String): void {

  }

  /**
   * Something happened and we need to update our filtering. This includes the tags or language changes. Afterwards, 'filteredPosts' should
   * contain the new modified list of posts.
   * @returns {Post[]}
   */
  updateFilteredPosts(language: string) {
    console.log('updating filtered posts for language ' + language);
    const res = new Array<Post>();
    if (this.allPosts == null) {
      return res;
    }
    for (const post of this.allPosts) {
      // console.log(post);
      if (this.stateService.shouldDisplay(post)) {
        // console.log('we should display this');
        // also check the language!
        // console.log(post.languages + ' ' + this.stateService.getLanguage());
        if (post.languages !== undefined && post.languages.indexOf(language) >= 0) {
          res.push(post);
        }
      } else {
        // console.log('we should not display this');
      }
    }
    // sort the posts
    console.log('sorting posts!');
    res.sort((p1, p2) => {
      console.log(p1.created_timestamp.getTime()+' '+p2.created_timestamp.getTime())
      return p2.created_timestamp.getTime() - p1.created_timestamp.getTime();
    });

    //set the result! this will update the list of the /posts page
    this.filteredPosts = res;
  }

  toggleTag(tag: string) {
    this.stateService.toggleTag(tag);
    this.updateFilteredPosts(this.stateService.getLanguage());
  }

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

}
