import { Component, Renderer2, ElementRef } from '@angular/core';
import { NavigationPanelService } from 'src/services/navigationPanel/navigation-panel.service';
import { ModalService } from 'src/services/modal/modal.service';

@Component({
  selector: 'app-journal-home',
  templateUrl: './journal-home.component.html',
  styleUrls: ['./journal-home.component.scss'],
})
export class JournalHomeComponent {
  private isNavigationOpen: boolean = false;
  private touchStartX: number = 0;
  public constructor(
    public navigation: NavigationPanelService,
    private renderer: Renderer2,
    private el: ElementRef,
    public modalService: ModalService,
  ) {}

  ngOnInit() {
    const width = window.innerWidth;
    this.navigation.showNavigationPanel$.subscribe((state) => {
      this.isNavigationOpen = state;
    });

    window.addEventListener('mousemove', (event) => {
      if (event.clientX < 10) {
      }
      if (
        event.clientX < 10 &&
        !this.isNavigationOpen &&
        !this.modalService.isModalOpen
      ) {
        this.navigation.openNavigation();
      }
    });

    window.addEventListener('mousemove', (event) => {
      if (event.clientX > width / 4 && this.isNavigationOpen) {
        this.navigation.closeNavigation();
      }
    });

    this.renderer.listen(
      this.el.nativeElement,
      'touchstart',
      this.onTouchStart.bind(this),
    );
    this.renderer.listen(
      this.el.nativeElement,
      'touchend',
      this.onTouchEnd.bind(this),
    );
  }

  onTouchStart(event: any) {
    this.touchStartX = event.touches[0].clientX;
  }

  onTouchEnd(event: any) {
    const touchEndX = event.changedTouches[0].clientX;
    if (touchEndX > this.touchStartX + 50) {
      this.navigation.openNavigation();
    } else if (touchEndX < this.touchStartX - 50) {
      this.navigation.closeNavigation();
    }
  }
}
