import {
  Component,
  ElementRef,
  HostListener,
  OnDestroy,
  OnInit,
  ViewChild,
} from "@angular/core";
import { MatDialog } from "@angular/material/dialog";
import { Router, NavigationStart } from "@angular/router";
import { marker } from "@biesbjerg/ngx-translate-extract-marker";
import { Subject } from "rxjs";
import { InviteUserDialogComponent } from "src/app/shared/dialogs/invite-user-dialog/invite-user-dialog.component";
import { AccountService } from "src/app/shared/server-services/account.service";
import { AuthService } from "src/app/shared/server-services/auth.service";
import {
  MeRecord,
  AccountAvatarRecord,
  UserRole,
} from "src/app/shared/server-services/query-records/account-records";
import { TimedOfferRecord } from "src/app/shared/server-services/query-records/timed-offer-records";
import { getTimedOffersQuery } from "src/app/shared/server-services/querys";
import { ResourceGroupService } from "src/app/shared/server-services/resource-group.service";
import {
  SubscriptionServiceEvent,
  SubscriptionServiceEventType,
} from "src/app/shared/server-services/subscription-event";
import { SubscriptionService } from "src/app/shared/server-services/subscription.service";
import { DialogService } from "src/app/shared/services/dialog.service";
import {
  FileManagerType,
  DownloadManagerService,
  downloadStartedObserver,
} from "src/app/shared/services/download-manager-service";
import {
  NanoActionType,
  NanoActionQueueService,
} from "src/app/shared/services/nano-action-queue.service";
import { ServerRestApiService } from "src/app/shared/services/server-rest-api.service";
import { EnvironmentService } from "src/environments/environment.service";
import { newsObserver } from "../resources-sidebar/resources-sidebar.component";
import { RouterHandler } from "../../shared/services/router-handler.service"

export let sideMenuActiveObserver = new Subject<boolean>();

export let showWorkspaceTabObserver = new Subject();

export let styleChangedObserver = new Subject<string>();

@Component({
  selector: "app-header",
  templateUrl: "./header.component.html",
  styleUrls: ["./header.component.scss"],
})
export class HeaderComponent implements OnInit, OnDestroy {
  public name = "guest";
  public colorTheme;
  public downloadProgress: FileManagerType[] = [];
  public actionList: NanoActionType[] = [];
  public accountMenuOpen: boolean = false;
  public playDownloadAnimation: boolean = false;
  public me: MeRecord;
  public isDistributor: boolean = false;
  public isAdmin: boolean = false;
  public webDocLink: string = marker("https://www.clarabot.info/nano/en/");
  public news: number = 0;
  public offersAvailable: boolean = false;
  public isAnonym: boolean = true;
  public isOnLoginPage: boolean = false;

  @ViewChild("menuToolbar", { read: ElementRef }) menuToolbar: ElementRef;
  @ViewChild("accountInfo", { read: ElementRef }) accountInfo: ElementRef;

  constructor(
    private authService: AuthService,
    private accountService: AccountService,
    private router: Router,
    private downloadManagerService: DownloadManagerService,
    private nanoActionQueueService: NanoActionQueueService,
    private dialogService: DialogService,
    private dialog: MatDialog,
    public environmentService: EnvironmentService,
    public resourceGroupService: ResourceGroupService,
    private subscriptionService: SubscriptionService,
    private serverRestApi: ServerRestApiService,
    private routerHandler: RouterHandler
  ) {

    this.colorTheme = localStorage.getItem("style_mode");
    styleChangedObserver.subscribe((style) => {
      this.colorTheme = style;
    });

    this.isOnLoginPage = this.routerHandler.isOnPage("login")
    this.routerHandler.subscribeAll((res)=>{
      this.isOnLoginPage = this.routerHandler.isOnPage("login")
    })

    this.isAnonym = this.authService.isAnonym();

    this.authService.onLogin(() => {
      
      console.log('header login happened')
      this.accountService.getMe().then((data) => {
        this.me = data;
        console.log('header me', this.me)
        this.isAnonym = false;
        this.isDistributor = this.accountService.isCurrentUserInRole(UserRole.DISTRIBUTOR, this.me);
        this.isAdmin = this.accountService.isCurrentUserInRole(UserRole.ADMIN, this.me);
      });
    });

    this.authService.onLogout(() => {
      console.log('header logout happened')
      this.accountService.getMe().then((data) => {
        this.me = data;
        console.log('header me', this.me)
        this.isAnonym = true;
      })
    });

    newsObserver.subscribe((news)=>{
      this.news = news;
    })

    router.events.subscribe((val) => {
      if (val instanceof NavigationStart) this.switchMenuOpen(false);
    });

    this.downloadProgress = downloadManagerService.getFileList();
    this.actionList = nanoActionQueueService.getActionList();

    downloadStartedObserver.subscribe((file: FileManagerType) =>
      this.downloadStartedEvent(file)
    );

    this.subscriptionService.subscribe(
      SubscriptionServiceEvent.ACCOUNT_EVENT,
      SubscriptionServiceEventType.MODIFY,
      this.onAccountChange.bind(this)
    );

    this.subscriptionService.subscribeWorkspaceLoaded(() => {
      this.serverRestApi.query({query: getTimedOffersQuery}).then((offers: TimedOfferRecord[]) => {
        this.offersAvailable = offers && offers.length > 0;
      });
    });
  }

  public onAccountChange(ev) {
    this.accountService.getMe().then((data) => {
      this.me = Object.assign({}, data);
      this.isAnonym = this.authService.isAnonym();
    });
  }

  ngOnInit(): void {
    this.accountService.getMe().then((data: MeRecord) => {
      console.log("me", data);
      this.me = data;
      this.isDistributor = this.accountService.isCurrentUserInRole(UserRole.DISTRIBUTOR, this.me);
      this.isAdmin = this.accountService.isCurrentUserInRole(UserRole.ADMIN, this.me);
    });
  }

  ngOnDestroy(){
    this.subscriptionService.unsubscribe(
      SubscriptionServiceEvent.ACCOUNT_EVENT,
      SubscriptionServiceEventType.MODIFY,
      this.onAccountChange.bind(this)
    );
  }

  downloadStartedEvent(file: FileManagerType) {
    this.playDownloadAnimation = true;
    setTimeout(() => {
      this.playDownloadAnimation = false;
    }, 3 * 1000);
  }

  burgerClick(shouldOpen: boolean = null): void {
    sideMenuActiveObserver.next(shouldOpen);
    showWorkspaceTabObserver.next();
  }

  showWorkSpaceTab(): void{
    showWorkspaceTabObserver.next();
  }

  switchMenuOpen(open: boolean = null) {
    this.accountMenuOpen = open != null ? open : !this.accountMenuOpen;
  }
  @HostListener("document:click", ["$event"])
  documentClick(event: MouseEvent) {
    if (
      !this.menuToolbar.nativeElement.contains(event.target) &&
      !this.accountInfo.nativeElement.contains(event.target)
    )
      this.switchMenuOpen(false);
  }

  openInviteDialog() {
    this.accountService.getAllAccount().then((partners) => {
      const dialogRef = this.dialog.open<
        InviteUserDialogComponent,
        AccountAvatarRecord[],
        AccountAvatarRecord[]
      >(InviteUserDialogComponent, {
        data: partners,
      });

      dialogRef.afterClosed().subscribe((result) => {
      });
    });
  }

}
