import { Component, OnInit,
  ChangeDetectorRef, ChangeDetectionStrategy } from '@angular/core'
import { Router, ActivatedRoute, ParamMap } from '@angular/router'
import { switchMap, map } from 'rxjs/operators'

import { DataService } from '../data.service'
import { All, Trail, Trails } from '../models'

@Component({
  selector: 'app-trail-detail',
  templateUrl: './trail-detail.component.html',
  styleUrls: ['./trail-detail.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class TrailDetailComponent implements OnInit {
  trail: Trail

  constructor(
    private route: ActivatedRoute,
    public router: Router,
    public dataService: DataService,
    public cdr: ChangeDetectorRef,
  ) { }

  ngOnInit(): void {
    this.route.paramMap.pipe(
      switchMap((params: ParamMap) =>
        this.dataService.all.pipe(map(
          (all: All) => all.trails[params.get('id')]
          )
        )
      )
    ).subscribe(
      trail => {
        this.trail = trail
        this.cdr.markForCheck()
      }
    )
  }

  showOnMap() {
    this.router.navigate(['map'], this.trail.mapRouteArgs)
  }
}
