/*
 This file is part of GNU Taler
 (C) 2022-2024 Taler Systems S.A.

 GNU Taler 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, or (at your option) any later version.

 GNU Taler 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
 GNU Taler; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>
 */

import {
  TalerFormAttributes,
  TalerProtocolDuration,
} from "@gnu-taler/taler-util";
import type {
  InternationalizationAPI,
  SingleColumnFormDesign,
  UIFormElementConfig,
} from "@gnu-taler/web-util/browser";

export type AcceptTermOfServiceContext = {
  tos_url: string;
  provider_name?: string;
  expiration_time?: TalerProtocolDuration;
  successor_measure?: string;
  tos_version: string;

  /**
   * Only open the attached link, do not offer both "view in browser"
   * and "download PDF" options.
   */
  link_only?: boolean;

  /**
   * @deprecated deprecated alias of tos_version.
   */
  tosVersion?: string;
};

/**
 *
 * @param i18n
 * @param context
 * @returns
 */
export function acceptTos(
  i18n: InternationalizationAPI,
  context: AcceptTermOfServiceContext,
): SingleColumnFormDesign {
  const myFields: UIFormElementConfig[] = [];

  if (context.link_only) {
    myFields.push({
      type: "external-link",
      id: TalerFormAttributes.DOWNLOADED_TERMS_OF_SERVICE,
      required: true,
      url: context.tos_url,
      label: i18n.str`Terms of service`,
      help: i18n.str`You must open/download the terms of service to proceed`,
    });
  } else {
    myFields.push(
      {
        type: "external-link",
        id: TalerFormAttributes.DOWNLOADED_TERMS_OF_SERVICE,
        required: true,
        url: context.tos_url,
        label: i18n.str`View in Browser`,
      },
      {
        type: "download-link",
        id: TalerFormAttributes.DOWNLOADED_TERMS_OF_SERVICE,
        url: context.tos_url,
        label: i18n.str`Download PDF version`,
        required: true,
        media: "application/pdf",
        help: i18n.str`You must download to proceed`,
      },
    );
  }

  return {
    type: "single-column" as const,
    fields: [
      ...myFields,
      {
        type: "toggle",
        id: TalerFormAttributes.ACCEPTED_TERMS_OF_SERVICE,
        required: true,
        trueValue: context.tos_version ?? context.tosVersion,
        onlyTrueValue: true,
        label: i18n.str`Do you accept the terms of service?`,
      },
    ],
  };
}
