import validate from 'validate.js';
import { match, isEmpty, is, pathOr, isNil } from 'ramda';
import CodiceFiscale from 'codice-fiscale-js';

export const isPIVA = (v) => {
    const regexp = new RegExp(/^[0-9]{11}$/);
    //console.log('isPIVA', !isEmpty(match(regexp, String(v))))
    return v && !isEmpty(v) && !isEmpty(match(regexp, String(v)));
}

// example: DSDDSD99P23B352G
export const isCodiceFiscale = (v) => {
    return v && !isEmpty(v) && CodiceFiscale.check(v);
}

export const isCAP = (v) => {
    const regexp = new RegExp(/^[0-9]{5}$/);
    return v && !isEmpty(v) && !isEmpty(match(regexp, String(v)));
}

export const isIBAN = (v) => {
    const regexp = new RegExp(/^((NO)[0-9A-Z]{2}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{3}|(NO)[0-9A-Z]{13}|(BE)[0-9A-Z]{2}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}|(BE)[0-9A-Z]{14}|(DK|FO|FI|GL|NL)[0-9A-Z]{2}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{2}|(DK|FO|FI|GL|NL)[0-9A-Z]{16}|(MK|SI)[0-9A-Z]{2}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{3}|(MK|SI)[0-9A-Z]{17}|(BA|EE|KZ|LT|LU|AT)[0-9A-Z]{2}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}|(BA|EE|KZ|LT|LU|AT)[0-9A-Z]{18}|(HR|LI|LV|CH)[0-9A-Z]{2}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{1}|(HR|LI|LV|CH)[0-9A-Z]{19}|(BG|DE|IE|ME|RS|GB)[0-9A-Z]{2}[ ][0-9A-Z]{4}[ ][0-9A-Z]{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[0-9A-Z]{28}|(MT)[0-9A-Z]{2}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{4}[ ][0-9A-Z]{3}|(MT)[0-9A-Z]{29})$/)
    return v && !isEmpty(v) && !isEmpty(match(regexp, v));
}

export const isEmail = (v) => {
    const constraints = {
        from: {
            email: true
        }
    };
    const res = validate({from: v}, constraints);
    return !res;
}

export const isEmailPEC = (v) => {
    const constraints = {
        from: {
            email: true
        }
    };
    const res = validate({from: v}, constraints);
    return !res;
}

export const isUrl = (v) => {
    const constraints = {
        from: {
            url: true
        }
    };
    const res = validate({from: v}, constraints);
    return !res;
}

export const isMarcaDaBollo = (v) => {
    const regexp = new RegExp(/^[0-9]{14}$/);
    return v && !isEmpty(match(regexp, String(v)));
}

export const minChecks = (v, num) => {
    return is(Array, v) ? v.length >= parseInt(num) : false;
}

export const maxChecks = (v, num) => {
    return is(Array, v) ? v.length <= parseInt(num) : false;
}

export const createSpreadsheetValidator = (gepafin) => (workbookValue) => {
    if (!gepafin || !workbookValue?.sheets) return true;
    const sheetId = workbookValue.sheetOrder?.[0];
    const sheet = sheetId
        ? workbookValue.sheets[sheetId]
        : Object.values(workbookValue.sheets)[0];
    const cellData = sheet?.cellData ?? {};

    const getCellValue = (key) => {
        const [r, c] = key.split(':');
        return cellData[r]?.[c]?.v;
    };

    for (const { key, errorMessage } of (gepafin.validationCells ?? [])) {
        const v = getCellValue(key);
        if (v === undefined || v === null || v === 0 || v === false || v === 'FALSE' || v === '') {
            return errorMessage || 'Validazione foglio di calcolo fallita';
        }
    }
    return true;
};

export const nonEmptyTables = (v = [], tableCfg = []) => {
    // table stores a plain array; criteria_table stores { rows: [...], total: N }
    const rows = is(Array, v) ? v : (v && is(Array, v.rows) ? v.rows : []);
    const colsCfg = pathOr([], ['stateFieldData'], tableCfg);
    const nonPredefinedCells = colsCfg
        .filter(o => !o.predefined)
        .map(o => o.name);
    let isTableValid = true;
    let atLeastOneCellFilled = false;

    // eslint-disable-next-line array-callback-return
    rows.map((row) => {
        if (isEmpty(row)) {
            isTableValid = false;
        } else {
            // eslint-disable-next-line array-callback-return
            nonPredefinedCells.map((k) => {
                if (isNil(row[k]) || isEmpty(row[k])) {
                    isTableValid = atLeastOneCellFilled;
                } else {
                    atLeastOneCellFilled = true;
                    isTableValid = true;
                }
            });
        }
    });

    return rows.length >= 1 && isTableValid;
}