// Copyright (C) 2023 WYATT GROUP
// Please see the AUTHORS file for details.
//
// super 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, either version 3 of the License, or
// any later version.
//
// super 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 super program. If not, see <https://www.gnu.org/licenses/>.

/// A helper class for getting theme elements.
abstract class ThemeHelper {
  /// Gets a theme element from a list of styles.
  /// Styles are checked in order, and the first one that passes the
  /// [valueValidator] is returned.
  /// Style elements are transformed using the [transform] function.
  ///
  /// [styles]: A list of styles that need to be checked.
  /// [transform]: A function that transforms each style element
  /// to a [T] type.
  /// [valueValidator]: An optional validation function that
  /// determines if a style element is valid.
  /// [combine]: A function that combines two [P] type objects to create
  /// a new object.

  static T? getThemeElement<P, T>(
    List<P?>? styles, {
    required T? Function(P?)? transform,
    bool? Function(P?)? valueValidator,
    P? Function(P?, P?)? combine,
  }) {
    final Iterable<P?>? validStyles = styles?.where(
      (element) => valueValidator?.call(element) ?? (element != null),
    );
    return (validStyles?.isNotEmpty ?? false)
        ? transform?.call(
            validStyles?.reduce(
              (value, element) => combine?.call(value, element) ?? value,
            ),
          )
        : null;
  }
}
