import { Component, OnDestroy, OnInit } from '@angular/core';
import { NbMediaBreakpointsService, NbSidebarService, NbThemeService, NbMenuItem, NbDialogService } from '@nebular/theme';

import { LayoutService } from '../../../@core/utils';
import { map, takeUntil } from 'rxjs/operators';
import { Subject } from 'rxjs';
import { ApiService } from '../../../frontcraft/services/login-api';
import { User } from '../../../../../../backend/Types/Types';
import { Router } from '@angular/router';
import { ChatComponent } from './chat.component';
import { ShoutMessage } from '../../../../../../backend/Components/Shoutbox/Interface';

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

  private destroy$: Subject<void> = new Subject<void>();
  user: User;
  title = "Loading ... ";

  themes = [
    {
      value: 'default',
      name: 'Light',
    },
    {
      value: 'dark',
      name: 'Dark',
    },
    {
      value: 'cosmic',
      name: 'Cosmic',
    },
    {
      value: 'corporate',
      name: 'Corporate',
    },
  ];

  currentTheme = 'default';
  userMenu : NbMenuItem[] = [ { title: 'Log out', link: '/auth/logout' } ];

  sendMessage: any = console.log
  chatwindow: ChatComponent
  chatlog: ShoutMessage[] = []
  newmessage = false
  lastmessage = "asdasd"

  constructor(private sidebarService: NbSidebarService,
              private router: Router,
              private themeService: NbThemeService,
              private layoutService: LayoutService,
              private breakpointService: NbMediaBreakpointsService,
              private api: ApiService,
              private dialogService : NbDialogService
             ) {}

  ngOnInit() {
    this.themeService.changeTheme("dark");

    this.currentTheme = this.themeService.currentTheme;

    this.user = this.api.getCurrentUser()
    if(this.user)
      this.userMenu.unshift({ title: 'Profile', link: '/frontcraft/user/'+this.user.username });
   
    this.api.get('GuildManager').getGuildInfo().then(info => {
      this.title = info.name
    })

    this.api.connectShoutbox((msg) => {
      this.chatlog.push(msg)
      if(msg.message != this.lastmessage)
        this.newmessage = true
      if(this.chatwindow) this.chatwindow.messages.push(msg)
    }).then(sendMsg => {
      this.sendMessage = (msg) => {
        sendMsg(msg)
        this.lastmessage = msg.message
      }
      this.api.get('Shoutbox').getFeed().then(log => {this.chatlog = log})
    })

    this.themeService.onThemeChange()
      .pipe(
        map(({ name }) => name),
        takeUntil(this.destroy$),
      )
      .subscribe(themeName => this.currentTheme = themeName);
  }

  openChat(){
    this.newmessage = false
    const ref = this.dialogService.open(ChatComponent, {
      context: {
        sendMessage: this.sendMessage,
      }
    });
    ref.onClose.subscribe(()=>{
      this.chatwindow = null
    })
    this.chatwindow = ref.componentRef.instance
    this.chatwindow.messages.push(...this.chatlog)
  }

  ngOnDestroy() {
    this.destroy$.next();
    this.destroy$.complete();
  }

  changeTheme(themeName: string) {
    this.themeService.changeTheme(themeName);
  }

  toggleSidebar(): boolean {
    this.sidebarService.toggle(true, 'menu-sidebar');
    this.layoutService.changeLayoutSize();

    return false;
  }

  logout() {
    this.api.logout()
  }

  navigateHome() {
    this.router.navigateByUrl('/')
    return false;
  }
}
