const handleSecretsChanged = (e) => {
  var secrets = e.detail;
  if (secrets != null) {
    console.log(
      "handleSecretsChanged,Have Secrets: Persist them Securely."
    );
    window.localStorage.setItem("secrets", JSON.stringify(secrets));
  } else {
      console.log(
      "handleSecretsChanged,Have Lost the Secrets, i.e. Unpaired. Destroy the persisted secrets."
    );
    window.localStorage.removeItem("secrets");
  }
  doSave(false, false);
};

const handleStatusChange = (e, spi) => {
    status = e.detail;
    console.log("handleStatusChange,detail:", e.detail);
    displayPairStatus(e.detail);
    hideDialog();
    
    if (status === SpiStatus.PairedConnected) {
    } else if (status === SpiStatus.Unpaired && !status.Finished) {
    } else if (status === SpiStatus.PairedConnecting) {
        updateDisplayContent('Contact staff for assistance');
    } else {
        doSave(false, false);
    }
};

const handleDeviceAddressChanged = (e, spi) => {
  let autoAddress = false;
  if ($("#rdAutoAddress").is(":checked")) {
    autoAddress = true;
  } else {
    return;
  }

  if (e != null) {
    if (e.detail.DeviceAddressResponseCode == "SUCCESS") {
        console.log("handleDeviceAddressChanged,detail:", e.detail);
      if (e.detail.Address != null && e.detail.Address != "") {
        $("#eftPosAddress").val(e.detail.Address);
        eftPosAddress = e.detail.Address;
      } else if (e.detail.ip != null && e.detail.ip != "") {
        $("#eftPosAddress").val(e.detail.ip);
        eftPosAddress = e.detail.ip;
      }
    }
  }
};

const handlePairingStatusChange = (e, spi) => {
    console.log("handlePairingStatusChange,detail:", e.detail);
    displayPairStatus(spi.CurrentStatus);
    hideDialog();
    if (e.detail != null) {
        updateDisplayContent(e.detail.Message);
        if (e.detail.Finished) {
            $('#btn-cancel').prop("disabled", true).hide();
            if (e.detail.Successful) {
                if (spi.CurrentStatus == SpiStatus.Unpaired) {
                    showDialog("Unpair Successful. ");
                    if (isSelfDevice) {
                        maintenanceContainer.hide();
                    }
                } else {
                    if (isSelfDevice) {
                        maintenanceContainer.show();
                    }
                }
            }
        } else if (
            e.detail.AwaitingCheckFromEftpos &&
            e.detail.AwaitingCheckFromPos
        ) {
            bootbox.confirm({
            message:
                `<p class="text-center">Please confirm the following code is shown on PINPAD:<br/> <h4 class="text-center">` +
                event.detail.ConfirmationCode +
                `</h4> </p>`,
            closeButton: false,
            buttons: {
                confirm: {
                label: "Yes",
                className: "btn-success",
                },
                cancel: {
                label: "No",
                className: "btn-danger",
                },
            },
            callback: function (result) {
                if (result) {
                console.log("pairingConfirmCode request");
                spi.PairingConfirmCode();
                hideDialog();
                } else {
                spi.PairingCancel();
                }
            },
            });
        }
        if (e.detail.Successful && e.detail.Finished) {
            spi.AckFlowEndedAndBackToIdle();
        }
    }
};

const handleTransactionMessageUpdateCallback = (e) => {
  console.log("handleTransactionMessageUpdateCallback.detail:", e.detail);
  const txnUpdateMessage = new TransactionUpdate(e.detail);
  updateDisplayContent(`${txnUpdateMessage.GetDisplayMessageText()}`);
};

const handleTxFlowStatusChangeCallback = (e, spi) => {
  console.log("handleTxFlowStatusChangeCallback.detail:", e.detail);
  updateDisplayContent(e.detail.DisplayMessage);
  if (e.detail.AwaitingSignatureCheck) {
      // Print the receipt: e.detail.SignatureRequiredMessage._receiptToSign
      printSignText(e);
    if (isSelfDevice) {
        hideDialog();
        bootbox.prompt({
            title: 'Please ask staff to help to process signature verification.',
            closeButton: false,
            centerVertical: true,
            inputType: 'password',
            callback: function (result) {
                 // TODO: Make the code editable
                if (result === '952700') {
                    hideDialog();
                    showSignDialog("Customer signature approved?");
                } else {
                    spi.AcceptSignature(false);
                }
            }
        });
    } else {
        showSignDialog("Customer signature approved?");
    }
  } else if (e.detail.AwaitingPhoneForAuth) {
    // Display the MOTO phone authentication UI
  } else if (e.detail.Finished) {
    switch (e.detail.Success) {
      case SuccessState.Success:
        // Display the successful transaction UI adding detail for user (e.detail.Response.Data.host_response_text)
        // Close the sale on the POS
        spi.AckFlowEndedAndBackToIdle();
        switch (e.detail.Type) {
          case TransactionType.Settle:
            doSaveSettlementResult(e);
            break;
          case TransactionType.Purchase:
            const purchaseResponse = new PurchaseResponse(e.detail.Response);
            console.log(
              "handleTxFlowStatusChangeCallback.purchaseResponse:",
              purchaseResponse
            );
            saveTxnSuccessResult(purchaseResponse, false);
            break;
          case TransactionType.Refund:
            const refundResponse = new RefundResponse(e.detail.Response);
            console.log(
              "handleTxFlowStatusChangeCallback.refundResponse:",
              refundResponse
            );
                saveTxnSuccessResult(refundResponse, true);
            break;
          case TransactionType.GetTransaction:
            case TransactionType.GetLastTransaction:
                
            break;
          default:
          // Perform actions after other transaction types
        }
        break;
      case SuccessState.Failed:
        spi.AckFlowEndedAndBackToIdle();
        // Display the failed transaction UI adding detail for user:
        // e.detail.Response.Data.error_detail
        // e.detail.Response.Data.error_reason
        // if (e.detail.Response.Data.host_response_text) {
        //     e.detail.Response.Data.host_response_text
            // }
            let response;
          switch (e.detail.Type) {
              case TransactionType.Purchase:
                  response = new PurchaseResponse(e.detail.Response);
                  console.log(
                      "handleTxFlowStatusChangeCallback.purchaseResponse:",
                      response
                  );
              break;
              case TransactionType.Refund:
                  response = new RefundResponse(e.detail.Response);
                  console.log(
                      "handleTxFlowStatusChangeCallback.refundResponse:",
                      response
                  );
              break;
            default:
                // Perform actions after other transaction types
            }

            if (response) {
                saveTxnFailResult(response, e.detail.Type === TransactionType.Refund);
                if (response.GetResponseCode() == 511) {
                    // Transaction Cancelled
                    window.hybridAPP.close(true);
                    return;
                }
            }

            if (e.detail.Response.Data.error_detail || e.detail.Response.Data.host_response_text) {
                bootbox.alert({
                    title: e.detail.Response.Data.error_detail || 'Transaction Failed',
                    message: e.detail.Response.Data.host_response_text || '',
                    callback: function () {
                        window.hybridAPP.close(true);
                    },
                });
                return;
            }

            window.hybridAPP.close(true);
        break;
        case SuccessState.Unknown:
            spi.AckFlowEndedAndBackToIdle();
            showUnknownDialog(e.detail.DisplayMessage);
        break;
      default:
      // Throw error: invalid success state
    }
  }
};

const printSignText = (e) => {
  var signReq = {};
  signReq.MachineID = machineID;
  signReq.SignatureMessage = e.detail.SignatureRequiredMessage._receiptToSign;
    signReq.EFTPOSType = EFTPOSType;

  console.log("signPrintCallback request.params:", signReq);
  $.ajax({
    type: "POST",
    url: "/api/eft/signPrintCallback",
    dataType: "json",
    contentType: "application/json;charset=UTF-8",
    headers: {
      Accept: "application/json; charset=utf-8",
      ContentType: "application/json; charset=utf-8",
      MerchantId: zmerchantId,
      BranchId: zbranchId,
    },
    data: JSON.stringify(signReq),
    success: function (result) {
      console.log("signPrintCallback response.result:", result);
    },
    error: function (e) {
        console.log("signPrintCallback response.error:", e.responseText);
    },
  });
};

const buildTransactionResult = (response, isRefund) => {
  const request = {};
  if (isRefund) {
    request.BaseAmount = transferAmtFromCent(response.GetRefundAmount());
    request.TransactionAmount = transferAmtFromCent(response.GetRefundAmount());
    request.TipAmount = 0;
    request.Surcharge = 0;
  } else {
    request.BaseAmount = transferAmtFromCent(response.GetPurchaseAmount());
    request.TransactionAmount = transferAmtFromCent(
      response.GetPurchaseAmount()
    );
    request.TipAmount = transferAmtFromCent(response.GetTipAmount());
    request.SurchargeAmount = transferAmtFromCent(
      response.GetSurchargeAmount()
    );
  }
  request.CustomerReceipt = response.GetCustomerReceipt();
  request.MerchantReceipt = response.GetMerchantReceipt();
  request.CardType = response.GetAccountType();
  request.TransactionReference = response.GetRRN();
  request.ResultText =
    response.GetResponseCode() + " " + response.GetResponseText();
  request.Result = "APPROVED";
  request.TransactionId = txn.TransactionId;
  request.MachineID = machineID;
  request.EftEnvironment = eftEnvironment;
  request.IsRefund = +isRefund;
    request.EFTPOSType = EFTPOSType;
    request.Seq = Seq;
  return request;
};

const saveTxnSuccessResult = async (response, isRefund) => {
    spi.AckFlowEndedAndBackToIdle();
  const request = buildTransactionResult(response, isRefund);
  try {
    $.ajax({
      type: "POST",
      url: "/api/eft/completeCallback",
      dataType: "json",
      contentType: "application/json;charset=UTF-8",
      headers: {
        Accept: "application/json; charset=utf-8",
        ContentType: "application/json; charset=utf-8",
        MerchantId: zmerchantId,
        BranchId: zbranchId,
      },
      data: JSON.stringify(request),
    });
      window.hybridAPP.close(true);
  } catch (e) {
    console.log("txn.completeCallback response.error:", e.responseText);
  }
};

const saveTxnFailResult = async (response, isRefund) => {
  spi.AckFlowEndedAndBackToIdle();
  const request = {};
  request.BaseAmount = txn.Amount;
  request.TransactionAmount = txn.Amount;
  request.TipAmount = 0;
  request.SurchargeAmount = 0;
    request.MerchantReceipt = response.GetMerchantReceipt() || '';
    request.CustomerReceipt = response.GetCustomerReceipt() || '';
  request.CardType = "";
  request.Result = "FAIL";
    request.ResultText = response.GetResponseCode() + " " + response.GetResponseText();
  request.TransactionId = txn.TransactionId;
  request.MachineID = machineID;
  request.EftEnvironment = eftEnvironment;
    request.TransactionReference = response.GetRRN() || '';
  request.IsRefund = +isRefund;
    request.EFTPOSType = EFTPOSType;

  console.log("txn.completeCallback request.params:", request);
  try {
    await $.ajax({
      type: "POST",
      url: "/api/eft/completeCallback",
      dataType: "json",
      contentType: "application/json;charset=UTF-8",
      headers: {
        Accept: "application/json; charset=utf-8",
        ContentType: "application/json; charset=utf-8",
        MerchantId: zmerchantId,
        BranchId: zbranchId,
      },
      data: JSON.stringify(request),
    });
  } catch (error) {
    console.log("trx.completeCallback response.error:", error);
  }
};


const doOverrideTransaction = (isSuccess) => {
    if (!txn.TransactionId) {
        return;
    }

    let overridReq = {};
    overridReq.TransactionId = txn.TransactionId;
    overridReq.MachineID = machineID;
    overridReq.IsSuccess = isSuccess;
    overridReq.EftEnvironment = eftEnvironment;
    overridReq.EFTPOSType = EFTPOSType;
    overridReq.Seq = Seq;

    console.log("overrideTransaction request.params:", overridReq);
    $.ajax({
        type: "POST",
        url: "/api/eft/overrideTransaction",
        dataType: "json",
        contentType: "application/json;charset=UTF-8",
        data: JSON.stringify(overridReq),
        headers: {
            Accept: "application/json; charset=utf-8",
            ContentType: "application/json; charset=utf-8",
            MerchantId: zmerchantId,
            BranchId: zbranchId
        },
        success: function (result) {
            console.log("retryTransaction response.result:", result);
            if (result.Code == "1000") {
                window.hybridAPP.close(true);
            }
            else {
                showDialog(result.Message);
            }
        },
        error: function (e) {
            console.log("retryTransaction response.error:", e.responseText);
            showDialog("Save failed. Please Retry.");
        }
    });
}

const doSaveSettlementResult = (e) => {
    const settlementResponse = new Settlement(e.detail.Response);
    const merchantReceipt = settlementResponse.GetReceipt().trim();
    const eftSettlementReq = {};
    eftSettlementReq.MachineID = machineID;
    eftSettlementReq.EFTPOSType = EFTPOSType;
    eftSettlementReq.MerchantReceipt = merchantReceipt;
    eftSettlementReq.PeriodStartTime = settlementResponse.GetPeriodStartTime();
    eftSettlementReq.PeriodEndTime = settlementResponse.GetPeriodEndTime();
    eftSettlementReq.SettlementTime = settlementResponse.GetTriggeredTime();
    eftSettlementReq.TransactionRange = settlementResponse.GetTransactionRange();
    eftSettlementReq.TerminalId = settlementResponse.GetTerminalId();
    eftSettlementReq.TotalCount = settlementResponse.GetTotalCount();
    eftSettlementReq.TotalValue = (
    settlementResponse.GetTotalValue() / 100.0
    ).toFixed(2);
    eftSettlementReq.AcquirerTXCount =
    settlementResponse.GetSettleByAcquirerCount();
    eftSettlementReq.AcquirerTXValue = (
    settlementResponse.GetSettleByAcquirerValue() / 100.0
    ).toFixed(2);

  console.log("config.settlementCallback request.params:", eftSettlementReq);
  $.ajax({
    type: "POST",
    headers: {
      Accept: "application/json; charset=utf-8",
      ContentType: "application/json; charset=utf-8",
      MerchantId: zmerchantId,
      BranchId: zbranchId,
    },
    url: "/api/eft/settlementCallback",
    data: JSON.stringify(eftSettlementReq),
    dataType: "json",
    contentType: "application/json;charset=UTF-8",
    success: function (result) {
      console.log("config.settlementCallback response.result:", result);
    },
    error: function (e) {
      console.log("config.settlementCallback resoinse.error:", e.responseText);
    },
  });
  const eftReq = {};
    eftReq.MachineID = machineID;
    eftReq.MerchantReceipt = merchantReceipt;
    eftReq.Seq = Seq;

  console.log("config.settlementPrintCallback request.params:", eftReq);
  $.ajax({
    type: "POST",
    headers: {
      Accept: "application/json; charset=utf-8",
      ContentType: "application/json; charset=utf-8",
      MerchantId: zmerchantId,
      BranchId: zbranchId,
    },
    url: "/api/eft/settlementPrintCallback",
    data: JSON.stringify(eftReq),
    dataType: "json",
    contentType: "application/json;charset=UTF-8",
    success: function (result) {
      console.log("config.settlementPrintCallback response.result", result);
    },
    error: function (e) {
      console.log(
        "config.settlementPrintCallback response.error:",
        e.responseText
      );
    },
  });
};
