import { Component, OnInit, Input, Output, EventEmitter, OnDestroy } from '@angular/core';
import { CommonService } from '../../services/common/common.service';
import { TranslatorService } from '../../services/translator/translator.service';
import { SegmentButton } from './segment.model';
import { Subscription } from 'rxjs';
import { Router, NavigationEnd } from '@angular/router';

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

  @Input() buttons: SegmentButton[];
  @Output() changed = new EventEmitter();
  @Input() floating = false;
  public activeSegment: string;
  public hide = false;
  private routerSubscription: Subscription;
  constructor(
    public cs: CommonService,
    public ts: TranslatorService,
    private router: Router
  ) { }

  ngOnInit() {
    if (this.floating) {
      this.routerSubscription = this.router.events.subscribe((val) => {
        // see also 
        if (val instanceof NavigationEnd) {
          this.hide = true;
        }
      });
    }
  }

  public ngOnDestroy(): void {
    if (this.routerSubscription) {
      this.routerSubscription.unsubscribe();
    }
  }


  @Input() set active(active: string) {
    if (active) {
      this.activeSegment = active;
      this.emitEvent(active);
    }

  }
  get active(): string {
    return this.activeSegment;
  }
  public onClick(button: SegmentButton) {
    if (button.id !== this.active) {
      this.active = button.id;
      this.emitEvent(button.id);
    }
  }

  private emitEvent(id: string) {
    this.changed.emit({
      detail: {
        value: id
      }
    });
  }

  public setActive(active: string) {
    this.activeSegment = active;
    this.emitEvent(active);
  }

}
