import ObjectFactory from '../../Utilities/ObjectFactory';
import { ApiBase } from '../Implementation/ApiBase';
import * as InternalRedux from '../../Redux/ActionsReducers/InternalRedux';
export class DataImportInternalApi extends ApiBase {
    async importData(partialRows) {
        const dataImportOptions = this.getOptions().dataImportOptions;
        let importData = partialRows;
        if (typeof dataImportOptions.handleImportedData === 'function') {
            const resolution = await dataImportOptions.handleImportedData({
                data: importData,
                ...this.getAdaptableInternalApi().buildBaseContext(),
            });
            if (resolution && resolution?.emitDataImportedEvent) {
                this.getEventApi().internalApi.fireDataImportedEvent(importData, resolution.addedRows, resolution.updatedRows);
            }
            return;
        }
        const gridApi = this.getGridApi();
        const primaryKey = this.getOptions().primaryKey;
        let newRowCount = 0;
        let updatedRowCount = 0;
        const preparedDataRows = importData.map((dataRow) => {
            const node = gridApi.getRowNodeForPrimaryKey(dataRow[primaryKey]);
            if (!node) {
                newRowCount += 1;
                return dataRow;
            }
            updatedRowCount += 1;
            return {
                ...node?.data,
                ...dataRow,
            };
        });
        const { addedRows, updatedRows } = await gridApi.addOrUpdateGridData(preparedDataRows);
        let message = '';
        if (newRowCount && updatedRowCount) {
            message = `Added: ${newRowCount} new Row${newRowCount > 1 ? 's' : ''}; Updated: ${updatedRowCount} existing Row${updatedRowCount > 1 ? 's' : ''}`;
        }
        else if (newRowCount && !updatedRowCount) {
            message = `Added: ${newRowCount} new Row${newRowCount > 1 ? 's' : ''}`;
        }
        else if (!newRowCount && updatedRowCount) {
            message = `Updated: ${updatedRowCount} existing Row${updatedRowCount > 1 ? 's' : ''}`;
        }
        const alert = {
            alertType: 'generic',
            header: 'Data Imported',
            message,
            alertDefinition: {
                ...ObjectFactory.CreateEmptyAlertDefinition(),
                MessageType: 'Info',
                AlertProperties: {
                    DisplayNotification: true,
                },
            },
        };
        this.getAlertApi().displayAdaptableAlert(alert);
        const dataImportedInfo = this.getEventApi().internalApi.fireDataImportedEvent(importData, addedRows, updatedRows);
        // Dispatch action (purely so it will be in Audit Log)
        this.getAdaptableInternalApi().dispatchReduxAction(InternalRedux.DataImportCompleted(dataImportedInfo));
    }
}
