import { Component, OnInit, Input, OnChanges, SimpleChanges, SimpleChange, ViewChild, ElementRef } from '@angular/core';
import { Router } from '@angular/router';
import { AuthenticationService } from '../authentication.service';

import * as $ from 'jquery';

@Component({
  selector: 'app-main-navigation',
  templateUrl: './main-navigation.component.html',
  styleUrls: ['./main-navigation.component.css']
})
export class MainNavigationComponent implements OnInit {
  currentUser;
  isLogin: Boolean;
  @ViewChild('menu') menu: ElementRef;
  @ViewChild('btn') btn: ElementRef;

  constructor(private router: Router, private authenticationService: AuthenticationService) {
    authenticationService.getLoggedInName.subscribe(name => this.isLoggedIn());
  }

  onOffMenuMobile() {
    console.log(this.menu.nativeElement.style.display);
    if (this.menu.nativeElement.style.display === '') {
      this.menu.nativeElement.style.display = 'none';
      this.btn.nativeElement.style.display = 'none';
      $('app-main-navigation ~ div.content').each(function () {
        $(this).css('position', 'static');
        $(this).css('margin-top', '0');
      });
    } else {
      if (this.menu.nativeElement.style.display === 'none') {
        this.menu.nativeElement.style.display = 'flex';
        this.btn.nativeElement.style.display = 'block';
        $('app-main-navigation ~ div.content').each(function () {
          $(this).css('position', 'fixed');
          $(this).css('margin-top', '195px');
        });
      } else {
        this.menu.nativeElement.style.display = 'none';
        this.btn.nativeElement.style.display = 'none';
        $('app-main-navigation ~ div.content').each(function () {
          $(this).css('position', 'position');
          $(this).css('margin-top', '0');
        });
      }
    }
  }

  navToProfile() {
    const currentUser = JSON.parse(localStorage.getItem('currentUser'));
    this.router.navigate(['/profile', currentUser.username]);
  }

  logout() {
    this.authenticationService.logout();
    this.router.navigate(['/home']);
    this.isLogin = false;
  }

  isLoggedIn() {
    if (localStorage.getItem('currentUser') === null) {
      this.isLogin = false;
    } else {
      this.isLogin = true;
    }
  }

  ngOnInit(): void {
    this.authenticationService.watchStorage().subscribe((data: string) => {
      this.currentUser = JSON.parse(localStorage.getItem('currentUser'));
      this.isLoggedIn();
    });
    this.authenticationService.watchStorageChanges();
  }

}
