import {DigitDependentLabelTemplate} from "./DigitDependentLabelTemplate";
import {TooltipCallbacksProvider} from "./TooltipCallbacksProvider";

export class DigitDependentTooltipLabelProvider implements TooltipCallbacksProvider {
  public templates: DigitDependentLabelTemplate[] = [];

  provideTooltipLabelCallback(): (label: string, formattedValue: string, raw: number) => string {
    const templates: DigitDependentLabelTemplate[] = this.templates;
    const excludedNumbers: number[] = [11, 12, 13, 14];

    return function (label: string, formattedValue: string, raw: number) {
      if (raw) {
        const template: DigitDependentLabelTemplate = templates
            .find(element => element.initialLabel === label);

        if (template) {
          const lastDigit = Math.abs(raw) % 10;
          const lastTwoDigits = Math.abs(raw) % 100;

          return formattedValue + " " + (excludedNumbers.includes(lastTwoDigits)
                                         ? template.otherDigitLabel
                                         : lastDigit == 1
                                           ? template.oneDigitLabel
                                           : lastDigit > 1 && lastDigit < 5
                                             ? template.fromTwoToFourDigitLabel
                                             : template.otherDigitLabel);
        }
      }
      return formattedValue ? formattedValue + " " + label : label;
    }
  }
}
