import { $DataFormats } from 'src/app/models/sas/editors-getdata.model'
import { Col } from '../models/col.model'
import { DcValidation } from '../models/dc-validation.model'

/**
 *  Merging old validation params from sasparams with cols params
 * @param sasparams sasparams coming from SAS
 * @param cols cols coming from SAS
 * @param rules Cell Validation rules to be updated
 * Those rules are passed in the `columns` property Of handsontable settings.
 * @returns
 */
export const mergeColsRules = (
  cols: Col[],
  rules: DcValidation[],
  $dataFormats: $DataFormats
): DcValidation[] => {
  for (let col of cols) {
    const rule = rules.find((x: DcValidation) => x.data === col.NAME)
    const colFormats = $dataFormats.vars[col.NAME]

    // Update COLS fields - it's passed by reference so this will update main object in editor component
    // DATE and TIME types are always numeric
    if (colFormats)
      col.TYPE = ['DATE', 'DATETIME', 'TIME'].includes(col.DDTYPE)
        ? 'num'
        : colFormats.type

    if (rule && col.DESC) rule.desc = col.DESC
    if (rule && colFormats.length) rule.length = parseInt(colFormats.length)
    if (rule && col.CLS_RULE) rule.clsRule = col.CLS_RULE
    if (rule && colFormats?.type) rule.sasType = colFormats.type
  }

  return rules
}
