import { ApplicationContext } from "@sankhyalabs/core";
export async function base64ToBlob(base64) {
  const response = await fetch(base64);
  return await response.blob();
}
export function buildFileKey(entityName, fieldName) {
  if (entityName) {
    return `${entityName}_${fieldName}`;
  }
  else {
    return fieldName;
  }
}
function hasSpecialCharacters(value) {
  const specialChars = /[ !@#$%^&*()+\-=\[\]{};':"\\|,.<>\/?]/;
  return specialChars.test(value);
}
/**
 * Gera a URL base para upload de sessão
 */
function getSessionUploadBaseUrl(fileKey, context = 'mge') {
  let url = `/${context}/sessionUpload.${context}?sessionkey=${fileKey}`;
  // Verifica se precisa processar caracteres especiais
  if (canProcessSpecialKeys(context) && hasSpecialCharacters(fileKey)) {
    url += `&encodedKey=${btoa(encodeURI(fileKey))}`;
  }
  return url;
}
/**
 * Verifica se pode processar chaves especiais
 * Baseado no método canProcessSpecialKeys do sessionfileupload.service.js
 */
async function canProcessSpecialKeys(context) {
  var _a;
  const application = ApplicationContext.getContextValue("__SNK__APPLICATION__");
  if (!application)
    return false;
  const resourceId = await ((_a = application.getResourceID) === null || _a === void 0 ? void 0 : _a.call(application)) || '';
  const adPrefix = "br.com.sankhya.menu.adicional";
  return context === 'mge' && resourceId.startsWith(adPrefix);
}
/**
 * Constrói a URL de upload
 * Baseado no método buildUploadURL do sessionfileupload.service.js
 */
function buildUploadURL(fileKey) {
  let url = getSessionUploadBaseUrl(fileKey);
  url += "&fitem=S&salvar=S&useCache=N";
  return url;
}
/**
 * Faz upload de arquivo para a sessão usando XMLHttpRequest
 * Baseado no método uploadSessionFile do sessionfileupload.service.js
 */
export async function sessionFileUpload(blob, entityName, fieldName, onProgress) {
  const fileKey = buildFileKey(entityName, fieldName);
  const uploadUrl = buildUploadURL(fileKey);
  return new Promise((resolve, reject) => {
    const formData = new FormData();
    formData.append('arquivo', blob);
    const http = new XMLHttpRequest();
    http.addEventListener("load", () => {
      if (http.status >= 200 && http.status < 300) {
        resolve(`/mge/UPLOADING_${fileKey}.dbimage`);
      }
      else {
        reject(new Error(`Upload failed: ${http.statusText}`));
      }
    });
    http.addEventListener("error", () => {
      reject(new Error('Upload error'));
    });
    if (onProgress) {
      http.upload.addEventListener("progress", onProgress);
    }
    http.open("POST", uploadUrl);
    http.send(formData);
  });
}
export function getUrlBase() {
  return window.location.origin;
}
export function getBaseUrl(pk, entityName, fieldName) {
  if (!pk)
    return undefined;
  const baseUrl = getUrlBase();
  let url = `${baseUrl}/mge/${entityName}@${fieldName}`;
  for (const pkField in pk) {
    url += `@${pkField}=${pk[pkField]}`;
  }
  url += '.dbimage';
  return url;
}
export function getPKs(dataUnit) {
  if (!dataUnit) {
    return undefined;
  }
  const pk = {};
  const fields = dataUnit.metadata.fields;
  const selectedRecord = dataUnit.getSelectedRecord();
  fields.forEach((field) => {
    if (field.properties['isPrimaryKey'] && selectedRecord) {
      pk[field.name] = selectedRecord[field.name];
    }
  });
  return pk;
}
export async function imageBlobToBase64(blob) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onloadend = () => {
      resolve(reader.result);
    };
    reader.onerror = reject;
    reader.readAsDataURL(blob);
  });
}
export async function downloadImage(pks, fieldName, entityName, signal) {
  const uploadUrl = getBaseUrl(pks, entityName, fieldName);
  if (!uploadUrl) {
    return;
  }
  try {
    const response = await fetch(uploadUrl, { signal });
    if (response.ok) {
      const blob = await response.blob();
      return await imageBlobToBase64(blob);
    }
  }
  catch (error) {
    if (signal === null || signal === void 0 ? void 0 : signal.aborted)
      return;
    console.error('Error downloading image:', error);
  }
}
