/*
 * Copyright (C) 2021 StApps
 * This program is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation, version 3.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <https://www.gnu.org/licenses/>.
 */

import {Injectable, Pipe, PipeTransform} from '@angular/core';
import moment from 'moment';

/**
 * Get the last value of an array
 */
@Injectable()
@Pipe({
  name: 'nextDateInList',
  pure: false, // pure pipe can break in some change detection scenarios,
  // specifically, on the calendar view it causes it to stay true even when you navigate
})
export class NextDateInListPipe implements PipeTransform {
  /**
   * Transform
   */
  // tslint:disable-next-line:prefer-function-over-method
  transform(dates: string[]): string {
    const nextDate = dates
      .sort((a, b) => moment(a).unix() - moment(b).unix())
      .find(date => {
        return moment(date).unix() > moment().unix();
      });
    return nextDate || '';
  }
}
