import {Injectable, OnInit} from '@angular/core';
import {Post} from '../model/post';
import {ActivatedRoute, ParamMap, Router} from '@angular/router';
import 'rxjs/add/operator/filter';

@Injectable()
export class StateService {
  // this keeps track of which type is enabled / disabled
  private tagFilter: any = [];
  private language: string;
  private rootRoute: ActivatedRoute;

  constructor(private router: Router) {
    router.events.subscribe(event => {
      // console.log('stateservice detects a route event!' + event);
    });
  }

  // /**
  //  * Get the language currently set in the router.
  //  *
  //  * @param {ActivatedRoute} route
  //  * @returns {Observable<string>}
  //  */
  // getLanguageFromRoute(route: ActivatedRoute): Observable<string> {
  //   return route.paramMap.map((params: ParamMap) => {
  //     const temp = params.get('language');
  //     return temp;
  //   });
  // }

  shouldDisplay(post: Post): boolean {

    // console.log('state service url: ' + this.router.url);

    // check whether all filters are true or false: that case, just show everything
    let foundTrue = false;
    let foundFalse = false;
    for (const tag of Object.keys(this.tagFilter)) {
      if (this.tagFilter[tag] === true) {
        foundTrue = true;
      }
      if (this.tagFilter[tag] === false) {
        foundFalse = true;
      }
    }
//    console.log('foundFalse: '+foundFalse);
//    console.log('foundTrue: '+foundTrue);
    if (!foundTrue && foundFalse) {
      return true;
    }
    if (!foundTrue && !foundFalse) {
      // some weird case, just show everything
      return true;
    }

    // check whether the post should be displayed
    for (const tag of Object.keys(this.tagFilter)) {
      if (post.tags.indexOf(tag) != -1 && this.tagFilter[tag] === true) {
        // found the tag and its filter is enabled
        return true;
      }
    }

    return false;
  }

  isActiveTag(tag: string): boolean {
    //  console.log('isActive');
    //  console.log(this.tagFilter);
    return this.tagFilter[tag] === true;
  }

  toggleTag(tag: string) {
    // console.log('toggle');
    // console.log(this.tagFilter);
    if (this.tagFilter[tag] == null) {
      this.tagFilter[tag] = true;
    } else {
      this.tagFilter[tag] = !this.tagFilter[tag];
    }
  }

  /**
   * Get the currently set language.
   * @returns {string}
   */
  getLanguage() {
    return this.language;
  }

  setLanguage(language: string, route: ActivatedRoute, router: Router) {
    console.log(`want to switch to: ${language} from ${this.language}`)
    if (this.language !== language) {
      console.log('setting language (triggers navigate): ' + language);
      this.language = language;

      console.log('GOING TO NAVIGATE!');
      console.log(this.rootRoute.url);

      //ok, don't know how to do this cleanly... figure out 2 elements
      //1:  the language, we already know it
      //2: the child path element, just get it from the rootroute
      if (this.rootRoute.children.length !== 1) {
        console.log('the root route has more than 1 child :/ NOT navigating now...');
        console.log(this.rootRoute.children);
      } else {
       const childRoute = this.rootRoute.children[0];
       // console.log('childroute: ' + childRoute.toString() + ' ' + childRoute.url.toString());
       // console.log(childRoute);
       const navigationpath = new Array<string>();
       navigationpath.push(language);
       childRoute.url.forEach(segments => {
         // console.log('url segments');
         // console.log(segments);
         //add each of these segments to the navigation path
         segments.forEach(s => navigationpath.push(s.path.toString()));
       });
       // console.log('OUR  navigation path');
       // console.log(navigationpath);
       //actually navigate!
       this.router.navigate(navigationpath);
      }

      this.rootRoute.pathFromRoot.forEach(p => console.log(p));
      this.rootRoute.firstChild.fragment.subscribe(val => {
        console.log('rootRoute.firstChild.fragment:  ' + val);
      });

      // router.navigate([language]);
    } else {
      console.log('setting language did nothing: no navigation.')
    }
  }

  getLanguageObservable() {
    return this.rootRoute.paramMap.map(map => map.get('language'));
  }

  setRootRoute(route: ActivatedRoute) {
    this.rootRoute = route;
    this.rootRoute.paramMap.map(map => map.get('language')).filter(l => l !== null).subscribe(l => {
        this.language = l;
        console.log('stateservice updated its internal lang value to ' + this.language);
      }
    )
    ;
  }
}
