import { Component, OnDestroy, OnInit, ViewChild, ViewEncapsulation } from '@angular/core';
import { Subscription } from 'rxjs';
import { LoanEditComponent } from './loan-edit/loan-edit.component';
import { AuthService } from './service/auth.service';
import { MenuService } from './service/menu.service';
import {WebSocketService} from './websocket';
import {Title} from '@angular/platform-browser';
import {WsLoginEventModel} from './models/websocket/ws.login.event.model';
import {SessionService} from './service/session.service';
import {environment} from '../environments/environment';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class AppComponent implements OnInit , OnDestroy {
  title = 'SFM Web Office';
  currentApplicationVersion = environment.appVersion;
  private menuItemSub: Subscription;
  @ViewChild('loanEditComponent', {static: true}) loanEdit: LoanEditComponent;

  webSocketSubscription: Subscription;
  wsAssignSocketIdSub: Subscription;
  wsLoginSub: Subscription;

  constructor(private menuService: MenuService,
              private authService: AuthService,
              private ss: SessionService,
              private wsService: WebSocketService,
              private titleService: Title){
    this.title = 'SFM Web Office (' + this.currentApplicationVersion + ')';
    this.webSocketSubscription = wsService.subscribe(m => {
        // console.log('websocket server send this :', m);
    });

    this.wsLoginSub = this.wsService.LoginEvent.subscribe( m => {
      this.onWSLogin(m);
    });

    this.wsAssignSocketIdSub = this.wsService.assignSocketIdEvent.subscribe(m =>{
      this.onWSAssignSocketId(m);
    });

    this.titleService.setTitle(this.title);
  }

  // tslint:disable-next-line:typedef
  ngOnInit() {
    this.listenToMenuEvent();
  }

  listenToMenuEvent(): void {
    this.menuItemSub = this.menuService.itemClicked.subscribe(
      (item: any) => {
        // console.log("emit on select : " + item.text);
        if ( item.popup ===  'loanEdit'){
        }
      }
    );
  }

  ngOnDestroy(): void {
    this.webSocketSubscription.unsubscribe();
    this.wsLoginSub.unsubscribe();
    this.wsAssignSocketIdSub.unsubscribe();
  }

  onWSLogin(e: WsLoginEventModel): void {
    if ( e.SocketId === this.ss.SocketId ) { // our own message
      return;
    }
    console.log('on login out', this);
    if ( e.T === 'logout' ) { // regardless where are they, logout means logout
      if ( this.ss.isLoggedIn() && this.ss.isCurrentUser(e.Uid) ) {
        if ( e.Mid === this.ss.MachineId ) {
          this.ss.logoutWithoutPersistingStorage();
        }else{
          this.ss.logout();
        }
      }
    }else{ // some one logged in from another browser tab
      if ( e.Mid === this.ss.loggedIn.machineId) { // same browser
        if ( !this.ss.isCurrentUser(e.Uid) ) {
          this.ss.logoutWithoutPersistingStorage();
        }
      }
    }
  }

  onWSAssignSocketId(id: string): void{
    console.log('get registration id', id);
    this.ss.SocketId = id;
  }
}

