


const chr = (codePt) => {
  if (codePt > 0xffff) {
    codePt -= 0x10000;
    return String.fromCharCode(0xd800 + (codePt >> 10), 0xdc00 + (codePt & 0x3ff));
  }
  return String.fromCharCode(codePt);
};

export const charToNum = (alpha) => {
  alpha = String(alpha).toUpperCase();
  let index = 0;
  for (let i = 0, j = 1; i < j; i++, j++) {
    if (alpha == numToChar(i)) {
      index = i;
      j = i;
    }
  }
  return index;
};

export const numToChar = (number) => {
  const numeric = (number - 1) % 26;
  const letter = chr(65 + numeric);
  const number2 = parseInt((number - 1) / 26);
  if (number2 > 0) {
    return numToChar(number2) + letter;
  }
  return letter;
};

export const toRoman = (num) => {
  var num = Math.floor(num);
  let val;
  let s = '';
  let i = 0;
  const v = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];
  const r = ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I'];

  function toBigRoman(n) {
    let ret = '';
    let n1 = '';
    let rem = n;
    while (rem > 1000) {
      let prefix = '';
      let suffix = '';
      var n = rem;
      const s = `${rem}`;
      let magnitude = 1;
      while (n > 1000) {
        n /= 1000;
        magnitude *= 1000;
        prefix += '(';
        suffix += ')';
      }
      n1 = Math.floor(n);
      rem = s - n1 * magnitude;
      ret += prefix + n1.toRoman() + suffix;
    }
    return ret + rem.toRoman();
  }

  if (num - num || num < 1) num = 0;
  if (num > 3999) return toBigRoman(num);

  while (num) {
    val = v[i];
    while (num >= val) {
      num -= val;
      s += r[i];
    }
    ++i;
  }
  return s;
};

export const fromRoman = (roman, accept) => {
  const s = roman.toUpperCase().replace(/ +/g, '');
  const L = s.length;
  let sum = 0;
  let i = 0;
  let next;
  let val;
  const R = {
    M: 1000, D: 500, C: 100, L: 50, X: 10, V: 5, I: 1,
  };

  function fromBigRoman(rn) {
    let n = 0;
    let x;
    let n1;
    let S;
    const rx = /(\(*)([MDCLXVI]+)/g;

    while ((S = rx.exec(rn)) != null) {
      x = S[1].length;
      n1 = Number.fromRoman(S[2]);
      if (isNaN(n1)) return NaN;
      if (x) n1 *= Math.pow(1000, x);
      n += n1;
    }
    return n;
  }

  if (/^[MDCLXVI)(]+$/.test(s)) {
    if (s.indexOf('(') == 0) return fromBigRoman(s);

    while (i < L) {
      val = R[s.charAt(i++)];
      next = R[s.charAt(i)] || 0;
      if (next - val > 0) val *= -1;
      sum += val;
    }
    if (accept || toRoman(sum) === s) return sum;
  }
  return NaN;
};
export const formatBytes = (bytes, decimals = 2) => {
  if (bytes === 0) {
    return '0 Bytes';
  }

  const k = 1024;
  const dm = decimals < 0 ? 0 : decimals;
  const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));

  return `${parseFloat((bytes / Math.pow(k, i)).toFixed(dm))} ${sizes[i]}`;
};
export const getPortalFilesUrl = () => `/Files?byPortal=true`
export const getProjectFilesPageUrl = (projectId: string) => `/project/${projectId}/listFiles?projectId=${projectId}`
export const getReviewUrl = (projectId: string, spaceId: string, reviewId: string) => `/review?reviewId=${reviewId}&spaceId=${spaceId}&projectId=${projectId}`
export const getViewerUrl = ({
  fileVersionId, transmittalVersionId, issueId, estimateId, measurementId, versionId, spaceId, scheduleId, projectId, contractId
}) => {
  const location = `/designviewer/file/${fileVersionId}`;
  const searchParams = new URLSearchParams('');

  if (scheduleId) {
    searchParams.set('scheduleId', scheduleId);
  }
  if (projectId) {
    searchParams.set('projectId', projectId);
  }
  if (spaceId) {
    searchParams.set('spaceId', spaceId);
  }
  if (contractId) {
    searchParams.set('contractId', contractId);
  }
  if (projectId) {
    searchParams.set('projectId', projectId);
  }
  if (transmittalVersionId) {
    searchParams.set('transmittalId', transmittalVersionId);
  }

  if (issueId) {
    searchParams.set('issueId', issueId);
  }

  if (estimateId) {
    searchParams.set('estimateId', estimateId);
    if (measurementId) {
      searchParams.set('measurementId', measurementId);
    }
    if (versionId) {
      searchParams.set('versionId', versionId);
    }
  }

  return `${location}?${searchParams.toString()}`;
};
export const getFilesGridColumns = ({
  openResourceTemplate, fileIdTemplate, fileNameTemplate, fileTypeTemplate, fileSizeTemplate, userAvatar, formatDate, conversionStatusTemplate, versionTemplate, statusInReviewTemplate, statusInReviewFilterTemplate, reviewSerialIdTemplate, reviewNameTemplate, workflowTemplate, currentReviewLevelSerialTemplate, currentReviewLevelNameTemplate, reviewCreatedDateTemplate, showProjectID, showMPMRCLColumns,
}) => [{
  field: '_id',
  headerText: '',
  width: '0',
  textAlign: 'Left',
  visible: false,
  freeze: 'Left',
  showInColumnChooser: false,
  isPrimaryKey: true,
  allowFiltering: false,
  allowEditing: false,
  allowSorting: false,
}, {
  field: '',
  width: '50',
  headerText: '',
  textAlign: 'Left',
  freeze: 'Left',
  template: openResourceTemplate,
  allowFiltering: false,
  allowEditing: false,
  allowSorting: false,
}, {
  field: 'fileId',
  headerText: 'File ID',
  width: '100',
  textAlign: 'Left',
  freeze: 'Left',
  template: fileIdTemplate,
  allowFiltering: false,
  allowEditing: false,
  allowSorting: false,
}, {
  field: 'fileName',
  width: '150',
  type: 'string',
  textAlign: 'Left',
  freeze: 'Left',
  template: fileNameTemplate,
  headerText: 'File Name',
  allowFiltering: true,
  allowEditing: false,
  allowSorting: true,
},
{
  field: 'fileType',
  headerText: 'File Type',
  width: '100',
  textAlign: 'Left',
  freeze: 'Left',
  template: fileTypeTemplate,
  allowFiltering: false,
  allowEditing: false,
  allowSorting: true,
}, {
  field: 'fileSize',
  headerText: 'File Size',
  width: '100',
  textAlign: 'Left',
  freeze: 'Left',
  template: fileSizeTemplate,
  allowFiltering: false,
  allowEditing: false,
  allowSorting: true,
},
{
  field: 'Version',
  headerText: 'Version',
  width: '100',
  textAlign: 'Left',
  freeze: 'Left',
  template: versionTemplate,
  allowFiltering: false,
  allowEditing: false,
  allowSorting: true,
},
{
  field: 'statusInReviews',
  headerText: 'Status',
  width: '170',
  type: 'string',
  textAlign: 'Left',
  freeze: 'Left',
  filter: { type: 'Menu' },
  template: statusInReviewTemplate,
  filterTemplate: statusInReviewFilterTemplate,
  allowFiltering: true,
  allowEditing: false,
  allowSorting: true,
}, {
  field: 'serialId',
  headerText: 'Review ID',
  width: '100',
  textAlign: 'Left',
  type: 'string',
  template: reviewSerialIdTemplate,
  allowFiltering: false,
  allowEditing: false,
  allowSorting: true,
},
{
  field: 'reviewName',
  headerText: 'Review Name',
  width: '150',
  textAlign: 'Left',
  type: 'string',
  template: reviewNameTemplate,
  allowFiltering: false,
  allowEditing: false,
  allowSorting: true,
},
{
  field: 'workflowName',
  headerText: 'Review Flow',
  width: '150',
  textAlign: 'Left',
  type: 'string',
  template: workflowTemplate,
  allowFiltering: false,
  allowEditing: false,
  allowSorting: true,
},
{
  field: 'currentReviewLevelSerial',
  headerText: 'Current Level ID',
  width: '150',
  textAlign: 'Left',
  type: 'string',
  template: currentReviewLevelSerialTemplate,
  allowFiltering: false,
  allowEditing: false,
  allowSorting: true,
},
{
  field: 'currentReviewLevelName',
  headerText: 'Current Level Name',
  width: '175',
  textAlign: 'Left',
  type: 'string',
  template: currentReviewLevelNameTemplate,
  allowFiltering: false,
  allowEditing: false,
  allowSorting: true,
},
{
  field: 'reviewCreatedDate',
  headerText: 'Review Created On',
  width: '175',
  textAlign: 'Left',
  type: 'string',
  template: reviewCreatedDateTemplate,
  allowFiltering: false,
  allowEditing: false,
  allowSorting: true,
},
...(showMPMRCLColumns) ? [{
  field: 'Title_mp',
  headerText: 'Title',
  width: '100',
  textAlign: 'Left',
  allowFiltering: true,
  allowSorting: true,
  allowEditing: false,
}, {
  field: 'Location_mp',
  headerText: 'Location',
  width: '100',
  textAlign: 'Left',
  allowFiltering: true,
  allowSorting: true,
  allowEditing: false,
}, {
  field: 'Remarks_mp',
  headerText: 'Remarks',
  width: '100',
  textAlign: 'Left',
  allowFiltering: true,
  allowSorting: true,
  allowEditing: false,
}] : [],
...(showProjectID) ? [{
  field: 'file.space.project.projectId',
  headerText: 'Project ID',
  width: '80',
  textAlign: 'Left',
  allowFiltering: true,
  allowSorting: true,
  allowEditing: false,
}] : [], {
  field: 'file.space.spaceName',
  headerText: 'Space',
  width: '120',
  textAlign: 'Left',
  allowFiltering: true,
  allowEditing: false,
  allowSorting: true,
},
{
  field: 'createdBy.fullName',
  headerText: 'Created By',
  width: '150',
  textAlign: 'Left',
  template: userAvatar,
  allowFiltering: true,
  allowEditing: false,
  allowSorting: true,
},
{
  field: 'createdDate',
  headerText: 'Created On',
  template: formatDate,
  width: '100',
  type: 'date',
  textAlign: 'Left',
  allowFiltering: false,
  allowEditing: false,
  allowSorting: true,
},
{
  field: 'conversionStatus',
  headerText: 'Conversion Status',
  width: '120',
  textAlign: 'Left',
  template: conversionStatusTemplate,
  allowFiltering: false,
  allowEditing: false,
  allowSorting: true,
}];

export const getFilesGridToolbar = ({ searchTemplate, excelExportTemplate }) => [
  {
    id: 'excel_export',
    align: 'Left',
    template: excelExportTemplate,
  },
  {
    id: 'search',
    align: 'Right',
    template: searchTemplate,
  },
];

export const conversionStatusTemplate=(params: {conversionStatus: string;}) => {
  let name; let tooltip;

  if(params.conversionStatus=='NOT_STARTED'||params.conversionStatus=='RETRY') {
    name='FileConversionStatusNotStarted';
    if(params.conversionStatus=='NOT_STARTED') {
      tooltip='Not Started';
    }
    else {
      tooltip='Retry';
    }
  }
  else if(params.conversionStatus=='IN_PROGRESS') {
    name='FileConversionStatusInProgress';
    tooltip='In Progress';
  }
  else if(params.conversionStatus=='COMPLETED') {
    name='FileConversionStatusSuccessfull';
    tooltip='Successful';
  }
  else if(params.conversionStatus=='ERRORED') {
    name='FileConversionStatusUnsuccessfull';
    tooltip='Failed';
  }
  else if(params.conversionStatus=='NOT_REQUIRED') {
    name='FileConversionStatusNotRequired';
    tooltip='Conversion Not Required';
  }
  else {
    return ('');
  }
  return (
    <div style={{width: '16px'}}>
      <ToolTipComponent position="BottomCenter" content={tooltip}>
        <IconComponent name={name} />
      </ToolTipComponent>
    </div>
  );
};