"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const React = __importStar(require("react"));
const PropTypes = __importStar(require("prop-types"));
const utils_1 = require("../../utils");
const VirtualSchemaField_1 = __importDefault(require("../VirtualSchemaField"));
/**
 * Combines values of two (or more) fields into one value which can be used for displaying (editing that value doesn't change formData)
 * Combine types:
 * timeDifference: combines the values by calculating their time difference
 * totalCount: combines the values by summing their counts together. if the value is an array the count is its length and if it is a number the count is the value
 * stringJoin (default): combines the values by joining them. delimiter is added between if given
 */
const combinedPropType = PropTypes.shape({
    firstField: PropTypes.string.isRequired,
    secondField: PropTypes.string.isRequired,
    additionalFields: PropTypes.arrayOf(PropTypes.string),
    name: PropTypes.string,
    title: PropTypes.string,
    combineType: PropTypes.string,
    delimiter: PropTypes.string
});
let CombinedValueDisplayField = class CombinedValueDisplayField extends React.Component {
    constructor() {
        super(...arguments);
        this.getFieldValue = (formData, field) => {
            return field[0] === "/" ? (0, utils_1.parseJSONPointer)(formData, field, !!"safely") : formData[field];
        };
        this.toMinutes = (time) => {
            const parts = time.split(":");
            return Number(parts[0]) * 60 + Number(parts[1]);
        };
        this.getCount = (value) => {
            return Array.isArray(value) ? value.length : (typeof value === "number" ? value : 0);
        };
        this.onChange = (formData) => {
            const uiOptions = this.getUiOptions();
            const combined = Array.isArray(uiOptions.combined) ? uiOptions.combined : [uiOptions.combined];
            const combinedFields = combined.map(options => {
                return options.name || "";
            }, []);
            combinedFields.forEach(field => {
                formData = (0, utils_1.immutableDelete)(formData, field);
            });
            this.props.onChange(formData);
        };
    }
    static getName() { return "CombinedValueDisplayField"; }
    getStateFromProps(props) {
        const uiOptions = this.getUiOptions();
        let { schema, idSchema, formData } = props;
        const combined = Array.isArray(uiOptions.combined) ? uiOptions.combined : [uiOptions.combined];
        combined.forEach(options => {
            const { name, title, combineType, firstField, secondField, additionalFields = [] } = options;
            schema = Object.assign(Object.assign({}, schema), { properties: Object.assign(Object.assign({}, schema.properties), { [name || ""]: { title: title || "", type: "string" } }) });
            idSchema = this.props.registry.schemaUtils.toIdSchema(schema, idSchema.$id);
            let value = undefined;
            const firstValue = this.getFieldValue(formData, firstField);
            const secondValue = this.getFieldValue(formData, secondField);
            const additionalValues = additionalFields.map(field => this.getFieldValue(formData, field));
            const allValues = [firstValue, secondValue].concat(additionalValues);
            if (combineType === "timeDifference") {
                if (firstValue && secondValue) {
                    const difference = this.toMinutes(secondValue) - this.toMinutes(formData[firstField]);
                    if (difference >= 0) {
                        const hours = Math.floor(difference / 60);
                        const minutes = difference % 60;
                        value = hours + " h " + minutes + " min";
                    }
                }
            }
            else if (combineType === "totalCount") {
                value = allValues.reduce((result, current) => result + this.getCount(current), 0);
            }
            else {
                const delimiter = options.delimiter || "";
                value = allValues.reduce((result, current) => {
                    if (current) {
                        result.push(current);
                    }
                    return result;
                }, []);
                value = value.join(delimiter);
            }
            formData = Object.assign(Object.assign({}, formData), { [name]: value });
        });
        return { schema, idSchema, formData, onChange: this.onChange };
    }
};
CombinedValueDisplayField.propTypes = {
    uiSchema: PropTypes.shape({
        "ui:options": PropTypes.shape({
            combined: PropTypes.oneOfType([
                combinedPropType,
                PropTypes.arrayOf(combinedPropType)
            ])
        }),
        uiSchema: PropTypes.object
    }).isRequired,
    schema: PropTypes.shape({
        type: PropTypes.oneOf(["object"])
    }).isRequired,
    formData: PropTypes.object.isRequired
};
CombinedValueDisplayField = __decorate([
    VirtualSchemaField_1.default
], CombinedValueDisplayField);
exports.default = CombinedValueDisplayField;
