"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 __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
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 VirtualSchemaField_1 = __importDefault(require("../VirtualSchemaField"));
const propsPropType = PropTypes.shape({
    from: PropTypes.string.isRequired,
    fromArrayKey: PropTypes.string,
    joinArray: PropTypes.bool,
});
/**
 * Watches a specified field which contains taxon set IDs.
 *
 * When taxon set IDs are added, it fetches the taxa in those sets from the API and adds them to the units in formData.
 *
 * When taxon set IDs are removed, it removes any taxa belonging to those sets from the units in formData.
 *
 * uiSchema = {
 *   "ui:field": "TaxonSetPopulatorField",
 *   "ui:options": {
 *     "props": {
 *       "from": "taxonCensus",                    	// Source object containing taxon set IDs
 *       "fromArrayKey": "censusTaxonSetID",      	// Field within source object containing the taxon set IDs
 *    	 "joinArray": true,                      	// Join array of IDs into comma-separated string
 *     }
 *   }
 * }
 */
let TaxonSetPopulatorField = class TaxonSetPopulatorField extends React.Component {
    constructor() {
        super(...arguments);
        this.selectedTaxonSets = [];
        this.unitTaxonSets = {};
        this.onChange = (formData) => __awaiter(this, void 0, void 0, function* () {
            var _a, _b, _c;
            const { translations } = this.props.formContext;
            const previousTaxonSets = this.selectedTaxonSets;
            const currentTaxonSets = ((_a = formData === null || formData === void 0 ? void 0 : formData.taxonCensus) === null || _a === void 0 ? void 0 : _a.map((item) => item.censusTaxonSetID)) || [];
            const deletedTaxonSets = previousTaxonSets.filter((item) => !currentTaxonSets.includes(item));
            const addedTaxonSets = currentTaxonSets.filter((item) => !previousTaxonSets.includes(item));
            this.selectedTaxonSets = ((_b = formData === null || formData === void 0 ? void 0 : formData.taxonCensus) === null || _b === void 0 ? void 0 : _b.map((item) => item.censusTaxonSetID)) || [];
            if (deletedTaxonSets.length > 0) {
                deletedTaxonSets.map((deletedTaxonSetId) => {
                    var _a;
                    const currentUnits = Array.isArray((_a = this.props.formData) === null || _a === void 0 ? void 0 : _a.units) ? this.props.formData.units : [];
                    let observationsExist = false;
                    const deletedTaxonSetUnits = currentUnits.filter((unit) => {
                        return this.unitTaxonSets[unit.identifications[0].taxonID]
                            && this.unitTaxonSets[unit.identifications[0].taxonID].includes(deletedTaxonSetId);
                    });
                    observationsExist = deletedTaxonSetUnits.some((unit) => {
                        var _a, _b, _c, _d;
                        return unit.maleIndividualCount ||
                            unit.femaleIndividualCount ||
                            unit.nestCount ||
                            ((_a = unit.unitFact) === null || _a === void 0 ? void 0 : _a.destroyedNestCount) ||
                            ((_b = unit.unitFact) === null || _b === void 0 ? void 0 : _b.broodCount) ||
                            ((_c = unit.unitFact) === null || _c === void 0 ? void 0 : _c.femalesWithBroodsCount) ||
                            ((_d = unit.unitFact) === null || _d === void 0 ? void 0 : _d.juvenileCount);
                    });
                    if (observationsExist) {
                        window.alert(translations === null || translations === void 0 ? void 0 : translations.TaxonSetDeletionFailed);
                        const restoredFormData = Object.assign(Object.assign({}, formData), { taxonCensus: [
                                ...formData.taxonCensus,
                                {
                                    censusTaxonSetID: deletedTaxonSetId,
                                    taxonCensusType: "MY.taxonCensusTypeCounted"
                                }
                            ] });
                        this.selectedTaxonSets = [...this.selectedTaxonSets, deletedTaxonSetId];
                        this.props.onChange(restoredFormData);
                        return;
                    }
                    const updatedUnits = currentUnits.filter((unit) => {
                        return !this.unitTaxonSets[unit.identifications[0].taxonID]
                            || !this.unitTaxonSets[unit.identifications[0].taxonID].includes(deletedTaxonSetId);
                    });
                    const updatedFormData = Object.assign(Object.assign({}, formData), { units: updatedUnits });
                    this.props.onChange(updatedFormData);
                });
                return;
            }
            if (addedTaxonSets.length > 0) {
                const currentUnits = Array.isArray((_c = this.props.formData) === null || _c === void 0 ? void 0 : _c.units) ? this.props.formData.units : [];
                // if current units include any units with taxon sets that are being added, return to avoid duplicates
                const duplicateUnits = currentUnits.filter((unit) => {
                    return this.unitTaxonSets[unit.identifications[0].taxonID]
                        && this.unitTaxonSets[unit.identifications[0].taxonID].some((taxonSetId) => addedTaxonSets.includes(taxonSetId));
                });
                if (duplicateUnits.length > 0) {
                    return;
                }
                const results = yield this.fetchTaxaFromSet(this.props, addedTaxonSets);
                const newUnits = results.map((result) => {
                    this.unitTaxonSets[result.id] = result.taxonSets || [];
                    return {
                        identifications: [{
                                taxon: result.scientificName,
                                taxonID: result.id,
                                taxonVerbatim: result.vernacularName
                            }],
                        informalTaxonGroups: result.informalTaxonGroups || []
                    };
                });
                const updatedFormData = Object.assign(Object.assign({}, formData), { units: [...currentUnits, ...newUnits] });
                this.props.onChange(updatedFormData);
                return;
            }
            this.props.onChange(formData);
        });
    }
    static getName() {
        return "TaxonSetPopulatorField";
    }
    getStateFromProps() {
        return { onChange: this.onChange };
    }
    componentDidMount() {
        return __awaiter(this, void 0, void 0, function* () {
            var _a, _b, _c;
            const taxonCensus = ((_a = this.props.formData) === null || _a === void 0 ? void 0 : _a.taxonCensus) || [];
            this.selectedTaxonSets = taxonCensus.map((item) => item.censusTaxonSetID);
            let resultTaxonSets = [];
            if (this.selectedTaxonSets.length > 0) {
                const allResults = yield Promise.all(this.selectedTaxonSets.map(taxonSetId => this.fetchTaxaFromSet(this.props, [taxonSetId])));
                resultTaxonSets = allResults.flat().map((result) => ({
                    id: result.id,
                    taxonSets: result.taxonSets || []
                }));
            }
            (_c = (_b = this.props.formData) === null || _b === void 0 ? void 0 : _b.units) === null || _c === void 0 ? void 0 : _c.forEach((unit) => {
                var _a, _b, _c;
                const taxonID = (_b = (_a = unit === null || unit === void 0 ? void 0 : unit.identifications) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.taxonID;
                if (!taxonID) {
                    return;
                }
                const taxonSets = ((_c = resultTaxonSets === null || resultTaxonSets === void 0 ? void 0 : resultTaxonSets.find((result) => result.id === taxonID)) === null || _c === void 0 ? void 0 : _c.taxonSets) || [];
                this.unitTaxonSets[taxonID] = taxonSets;
            });
        });
    }
    fetchTaxaFromSet(props, taxonSets) {
        return __awaiter(this, void 0, void 0, function* () {
            var _a;
            const apiClient = (_a = props.formContext) === null || _a === void 0 ? void 0 : _a.apiClient;
            if (!apiClient) {
                return [];
            }
            try {
                const response = yield apiClient.post("/taxa", {
                    query: {
                        pageSize: 1000,
                        selectedFields: ["id", "scientificName", "vernacularName", "informalTaxonGroups", "taxonSets"]
                    }
                }, {
                    taxonSets
                });
                if (!response.results || !Array.isArray(response.results)) {
                    return [];
                }
                return response.results;
            }
            catch (error) {
                return [];
            }
        });
    }
};
TaxonSetPopulatorField.propTypes = {
    uiSchema: PropTypes.shape({
        "ui:options": PropTypes.shape({
            props: PropTypes.oneOfType([PropTypes.arrayOf(propsPropType), propsPropType])
        }),
        uiSchema: PropTypes.object
    }).isRequired,
    schema: PropTypes.shape({
        type: PropTypes.oneOf(["array", "object"])
    }).isRequired,
    formData: PropTypes.oneOfType([PropTypes.array, PropTypes.object]).isRequired
};
TaxonSetPopulatorField = __decorate([
    VirtualSchemaField_1.default
], TaxonSetPopulatorField);
exports.default = TaxonSetPopulatorField;
