import { Component, OnInit } from '@angular/core';
import { NavigationEnd, Router } from '@angular/router';
import { BixiI18nService, en_US, zh_CN } from '@bixi/core/i18n';
import { filter } from 'rxjs/operators';
import { I18NService } from '../../core/i18n/service';
import { MetaService } from '../../core/meta.service';
import { MobileService } from '../../core/mobile.service';
import { MetaSearchGroup, MetaSearchGroupItem } from '../../interfaces';

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  host: {
    '[attr.id]': '"header"'
  }
})
export class HeaderComponent implements OnInit {
  constructor(
    public i18n: I18NService,
    private router: Router,
    private mobileSrv: MobileService,
    private meta: MetaService,
    private bixiI18n: BixiI18nService
  ) {
    router.events.pipe(filter(evt => evt instanceof NavigationEnd)).subscribe(() => (this.menuVisible = false));
    this.mobileSrv.change.subscribe(res => (this.isMobile = res));
  }

  isVisible = true;
  isMobile: boolean;
  oldVersionList = ['stable'];
  currentVersion = 'stable';
  currentLang = 'zh';
  langList = [{ title: 'English', value: 'en' }, { title: '中文', value: 'zh' }];
  solutions = [
    {
      name: 'auth',
      link: '/auth/getting-started'
    },
    {
      name: 'ac',
      link: '/ac/getting-started'
    },
    {
      name: 'mock',
      link: '/mock/getting-started'
    },
    {
      name: 'label',
      link: '/label/getting-started'
    }
  ];

  menuVisible = false;
  list: MetaSearchGroup[] = [];

  ngOnInit(): void {
    const lang = this.i18n.lang.slice(0, 2);
    if (this.currentLang !== lang) {
      this.toLang(lang as 'zh' | 'en');
    }
    this.currentLang = lang;
  }

  toVersion(version: string) {
    if (version !== this.currentVersion) {
      window.location.href = `https://bixi.datagrand.com/${version}-doc/`;
    }
  }

  toLang(language: 'en' | 'zh') {
    this.router.navigateByUrl(`${this.i18n.getRealUrl(this.router.url)}/${language}`);
    if (language === 'zh') {
      this.bixiI18n.setLocale(zh_CN);
    } else {
      this.bixiI18n.setLocale(en_US);
    }
  }
  // tslint:disable-next-line: no-any
  changeQ(value: any) {
    this.list = this.meta.search(value);
  }

  to(item: MetaSearchGroupItem) {
    if (item.url) {
      this.router.navigateByUrl(item.url);
    }
  }

  toViaMobile(url: string) {
    this.router.navigateByUrl(`${url}/${this.i18n.zone}`).then(() => {
      this.menuVisible = false;
    });
  }
}
