import {
  Component,
  OnInit,
  Input,
  Output,
  EventEmitter,
  ViewChild,
  Optional
} from '@angular/core';
import { ucapAnimations } from '../animations';
import { MatCalendar, DateAdapter } from '@angular/material';
import { Subject } from 'rxjs';
import { TranslateService } from '@ngx-translate/core';

@Component({
  selector: 'ucap-pick-date',
  templateUrl: './pick-date.component.html',
  styleUrls: ['./pick-date.component.scss'],
  animations: ucapAnimations
})
export class PickDateComponent<D> implements OnInit {
  @Input()
  initSelected: D;

  @Output()
  readonly selected: EventEmitter<D> = new EventEmitter<D>();

  @Output()
  readonly yearSelected: EventEmitter<D> = new EventEmitter<D>();

  @Output()
  readonly monthSelected: EventEmitter<D> = new EventEmitter<D>();

  @ViewChild('calendar', { static: true })
  calendar: MatCalendar<D>;

  // tslint:disable-next-line: variable-name
  constructor(
    @Optional() private _dateAdapter: DateAdapter<D>,
    private translateService: TranslateService
  ) {
    this._dateAdapter.setLocale(this.translateService.currentLang);
  }

  ngOnInit() {}

  /** Selects the given date */
  select(date: D): void {
    const oldValue = this.initSelected;
    this.initSelected = date;
    if (!this._dateAdapter.sameDate(oldValue, this.initSelected)) {
      this.selected.emit(date);
    }
  }

  /** Emits the selected year in multiyear view */
  _selectYear(normalizedYear: D): void {
    this.yearSelected.emit(normalizedYear);
  }

  /** Emits selected month in year view */
  _selectMonth(normalizedMonth: D): void {
    this.monthSelected.emit(normalizedMonth);
  }
}
