"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 __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 immutability_helper_1 = __importDefault(require("immutability-helper"));
const equals = require("deep-equal");
const utils_1 = require("../../utils");
const isomorphic_fetch_1 = __importDefault(require("isomorphic-fetch"));
const Context_1 = __importDefault(require("../../Context"));
const ReactContext_1 = __importDefault(require("../../ReactContext"));
const components_1 = require("../components");
const react_spinner_1 = __importDefault(require("react-spinner"));
const cache = {};
class GeocoderField extends React.Component {
    static getName() { return "GeocoderField"; }
    constructor(props) {
        super(props);
        this.onLocate = (geometry) => {
            this.updateForGeometry(this.props, undefined, this.normalizeGeometry(geometry));
        };
        this.getOptions = (props) => {
            return Object.assign({ updateOnlyEmpty: false, button: false, fields: ["country", "municipality", "biologicalProvince", "biogeographicalProvince", "administrativeProvince"] }, (0, utils_1.getUiOptions)((props || this.props).uiSchema));
        };
        this.onButtonClick = () => () => {
            this.mounted ? this.setState(this.getStateFromProps(this.props, true), () => {
                this.update(this.props, (failed = false) => {
                    this.fetchedButton = this.fetchedButton ? this.fetchedButton + 1 : 1;
                    this.mounted && this.setState(Object.assign(Object.assign({}, this.getStateFromProps(this.props, false)), { timeout: failed }));
                });
            }) :
                this.update(this.props, (failed = false) => {
                    this.mounted && this.setState(Object.assign(Object.assign({}, this.getStateFromProps(this.props, false)), { timeout: failed }));
                });
        };
        this.getGeometry = (props) => {
            const { uiSchema, formData = {} } = props;
            const { geometryField = "geometry" } = (0, utils_1.getUiOptions)(uiSchema);
            let geometry = this.normalizeGeometry(formData[geometryField]);
            // TODO misses geometry collections
            if (formData.units)
                formData.units.forEach(({ unitGathering }) => {
                    if (unitGathering && unitGathering.geometry && unitGathering.geometry.coordinates) {
                        geometry = (0, immutability_helper_1.default)(geometry, { geometries: { $push: [unitGathering.geometry] } });
                    }
                });
            return geometry;
        };
        this.normalizeGeometry = (geometry) => {
            if (!geometry || !geometry.type) {
                geometry = { type: "GeometryCollection", geometries: [] };
            }
            else if ("type" in geometry && geometry.type !== "GeometryCollection") {
                geometry = { type: "GeometryCollection", geometries: [geometry] };
            }
            return geometry;
        };
        this.fetch = (url) => {
            cache[url] = cache[url] || (0, isomorphic_fetch_1.default)(url).then(response => {
                if (response.status >= 400) {
                    throw new Error(this.props.formContext.translations.RequestFailed);
                }
                return response.json();
            }).catch(() => {
                delete cache[url];
                throw new Error(this.props.formContext.translations.RequestFailed);
            });
            return cache[url];
        };
        this.update = (props, callback) => {
            const geometry = this.getGeometry(props);
            this.updateForGeometry(props, callback, geometry);
        };
        this.getComponentContext = () => {
            return (0, Context_1.default)(`${this.props.formContext.contextId}_${(0, utils_1.getFieldUUID)(this.props)}_GEOCODERFIELD`);
        };
        this.updateForGeometry = (props, callback, geometry) => {
            const { fields } = this.getOptions();
            const fieldByKeys = fields.reduce((_fields, option) => {
                _fields[option] = true;
                return _fields;
            }, {});
            if (!geometry || !geometry.geometries || !geometry.geometries.length) {
                this.mounted && this.setState(this.getStateFromProps(props, false));
                return;
            }
            const join = (oldValue, value) => (0, utils_1.isEmptyString)(oldValue) ? value : `${oldValue}, ${value}`;
            const lajiFormInstance = props.formContext.services.rootInstance;
            const timestamp = Date.now();
            this.promiseTimestamp = timestamp;
            const doAsync = () => {
                this.getComponentContext().hook = props.formContext.services.submitHooks.add(props, () => new Promise((resolve, reject) => {
                    const afterFetch = (callback, timeout = false) => {
                        if (this.getComponentContext().fetching) {
                            if (callback)
                                callback(timeout);
                        }
                        this.getComponentContext().fetching = false;
                        if (this.getComponentContext().resetRemountedState)
                            this.getComponentContext().resetRemountedState(false);
                    };
                    const success = (callback, timeout) => {
                        afterFetch(callback, timeout);
                        resolve();
                    };
                    const fail = (e, callback, timeout) => {
                        afterFetch(callback, timeout);
                        reject(e);
                    };
                    const handleResponse = (...fields) => (response) => {
                        fields = fields.reduce((_fields, field) => {
                            _fields[field] = true;
                            return _fields;
                        }, {});
                        const changes = {};
                        if (fieldByKeys.biologicalProvince) {
                            changes.biologicalProvince = undefined;
                        }
                        if (fieldByKeys.biogeographicalProvince) {
                            changes.biogeographicalProvince = undefined;
                        }
                        if (fieldByKeys.administrativeProvince) {
                            changes.administrativeProvince = undefined;
                        }
                        const parsers = {
                            country: {
                                type: ["country"],
                                responseField: "long_name"
                            },
                            administrativeProvince: {
                                type: ["administrative_area_level_1"],
                                responseField: "long_name"
                            },
                            municipality: {
                                type: ["municipality", "administrative_area_level_3", "administrative_area_level_2"],
                                responseField: "long_name"
                            },
                            biologicalProvince: {
                                type: ["biogeographicalProvince"],
                                responseField: "long_name"
                            },
                            biogeographicalProvince: {
                                type: ["biogeographicalProvince"],
                                responseField: "long_name"
                            }
                        };
                        const found = {};
                        Object.keys(parsers).forEach(field => {
                            const parser = parsers[field];
                            parser.type.some((type, typeIdx) => {
                                response.results.forEach(result => result.address_components.forEach(addressComponent => {
                                    if (addressComponent.types.includes(type)) {
                                        if (!found[field])
                                            found[field] = {};
                                        if (!found[field][typeIdx])
                                            found[field][typeIdx] = {};
                                        const responseField = addressComponent[parser.responseField] ? parser.responseField : "short_name";
                                        found[field][typeIdx][addressComponent[responseField]] = true;
                                    }
                                }));
                                return found[field] && found[field][typeIdx];
                            });
                        });
                        Object.keys(parsers).forEach(field => {
                            if (!fieldByKeys[field] || !this.props.schema.properties[field]) {
                                return;
                            }
                            if (found[field]) {
                                const keys = Object.keys(found[field]);
                                const responseForField = found[field][keys[0]];
                                Object.keys(responseForField).forEach(value => {
                                    // If target field is array.
                                    if (this.props.schema.properties[field].type === "array") {
                                        const temp = Array.from((this.props.formData || {})[field] || []);
                                        // Find correct enum from fieldOptions.
                                        const fieldOptions = this.props.uiSchema["ui:options"].fieldOptions;
                                        const enumField = fieldOptions[fieldOptions.findIndex(element => {
                                            return element.field === field;
                                        })].enum;
                                        // Find enum value from key (eg. municipalityName --> municipalityId).
                                        const _enum = this.props.formContext.uiSchemaContext[enumField].oneOf;
                                        const enumValue = _enum.find(item => item.title === value).const;
                                        // Push enum value to changes.
                                        if (enumValue !== undefined) {
                                            !temp.includes(enumValue) && temp.push(enumValue);
                                            changes[field] = temp;
                                        }
                                    }
                                    else {
                                        changes[field] = join(changes[field], value);
                                    }
                                });
                            }
                            else {
                                changes[field] = (0, utils_1.getDefaultFormState)(this.props.schema.properties[field]);
                            }
                        });
                        success(() => {
                            if (timestamp !== this.promiseTimestamp)
                                return;
                            if (this.mounted) {
                                this.props.onChange(Object.assign(Object.assign({}, (this.props.formData || {})), changes));
                            }
                            else {
                                const pointer = this.props.formContext.services.ids.getJSONPointerFromLajiFormIdAndFormDataAndIdSchemaId(this.props.idSchema.$id, (0, utils_1.getFieldUUID)(this.props));
                                const newFormData = Object.assign(Object.assign({}, (0, utils_1.parseJSONPointer)(lajiFormInstance.getFormData(), pointer)), changes);
                                lajiFormInstance.onChange((0, utils_1.updateSafelyWithJSONPointer)(lajiFormInstance.getFormData(), newFormData, pointer));
                            }
                            if (callback)
                                callback();
                        });
                    };
                    this.getComponentContext().fetching = true;
                    this.props.formContext.setTimeout(() => {
                        if (timestamp !== this.promiseTimestamp)
                            return;
                        if (this.getComponentContext().fetching) {
                            fail(this.props.formContext.translations.GeocodingTimeout);
                            this.mounted && this.setState({ timeout: true }, () => {
                                this.mounted && this.setState(this.getStateFromProps(this.props, false));
                            });
                        }
                    }, 30 * 1000);
                    this.props.formContext.apiClient.post("/coordinates/location", undefined, geometry).then(handleResponse("country", "municipality", "administrativeProvince", "biologicalProvince", "biogeographicalProvince")).catch(e => {
                        fail(typeof e === "string" ? e : e.message);
                    });
                }));
            };
            if (this.getComponentContext().hook) {
                this.props.formContext.services.submitHooks.remove((0, utils_1.getFieldUUID)(this.props), this.getComponentContext().hook).then(doAsync);
            }
            else {
                doAsync();
            }
        };
        const loading = this.getComponentContext().fetching;
        this.state = this.getStateFromProps(props, loading);
    }
    UNSAFE_componentWillReceiveProps(props) {
        const geometryUpdated = equals(this.getGeometry(props), this.getGeometry(this.props)) ? false : undefined;
        this.setState(this.getStateFromProps(props, geometryUpdated));
    }
    componentDidMount() {
        this.mounted = true;
        this.componentDidUpdate();
        this.props.formContext.services.customEvents.add(this.props.idSchema.$id, "locate", this.onLocate);
        this.getComponentContext().resetRemountedState = (loading) => this.setState(this.getStateFromProps(this.props, loading));
    }
    componentWillUnmount() {
        this.mounted = false;
        this.props.formContext.services.customEvents.remove(this.props.idSchema.$id, "locate", this.onLocate);
        delete this.getComponentContext().resetRemountedState;
    }
    componentDidUpdate(prevProps) {
        const { updateOnlyEmpty, button, fields } = this.getOptions(this.props);
        const hasData = fields.some(field => !(0, utils_1.isEmptyString)((this.props.formData || {})[field]));
        const geometry = this.getGeometry(this.props);
        const geometriesEqual = prevProps && equals(this.getGeometry(prevProps), geometry);
        const geometryEmpty = geometry && geometry.geometries && geometry.geometries.length === 0;
        if (updateOnlyEmpty && !geometryEmpty && hasData) {
            return;
        }
        if (!prevProps && hasData) {
            return;
        }
        if ((geometryEmpty && prevProps && !geometriesEqual) // was emptied
            ||
                (((this.state.loading === undefined && !this.state && geometry) || !geometriesEqual))) {
            button ? this.onButtonClick()() : this.update(this.props);
        }
    }
    getStateFromProps(props, loading) {
        const state = { loading };
        const { button } = this.getOptions(props);
        const innerUiSchema = (0, utils_1.getInnerUiSchema)(props.uiSchema);
        if (button) {
            state.uiSchema = Object.assign(Object.assign({}, innerUiSchema), { "ui:options": Object.assign(Object.assign({}, (0, utils_1.getUiOptions)(innerUiSchema)), { buttons: [
                        ...((0, utils_1.getUiOptions)(innerUiSchema).buttons || []),
                        this.getButton(props, loading)
                    ] }) });
        }
        else {
            state.uiSchema = innerUiSchema;
        }
        return state;
    }
    getButton(props, loading) {
        // Button is disabled when loading is false 
        // (it is false only after fetch and no formData updates, otherwise it will be true/undefined.
        const geometry = this.getGeometry(props);
        return {
            fn: this.onButtonClick,
            position: "top",
            key: loading,
            render: onClick => (React.createElement(components_1.Button, { key: "geolocate", onClick: onClick, disabled: loading || props.disabled || props.readonly || !this.state.timeout && (loading === false || !geometry || !geometry.geometries || geometry.geometries.length === 0), className: "geocoder-btn" },
                loading ? React.createElement(react_spinner_1.default, null) : React.createElement(ReactContext_1.default.Consumer, null, ({ theme: { Glyphicon } }) => React.createElement(Glyphicon, { glyph: "globe" })),
                " ",
                props.formContext.translations.Geolocate))
        };
    }
    render() {
        const { SchemaField } = this.props.registry.fields;
        return React.createElement(SchemaField, Object.assign({}, this.props, { uiSchema: this.state.uiSchema }));
    }
}
GeocoderField.propTypes = {
    uiSchema: PropTypes.shape({
        "ui:options": PropTypes.shape({
            updateOnlyEmpty: PropTypes.bool,
            button: PropTypes.bool,
            fields: PropTypes.arrayOf(PropTypes.oneOf((["country", "municipality",
                "biologicalProvince", "biogeographicalProvince", "administrativeProvince"]))),
            geometryField: PropTypes.string,
            "fieldOptions": PropTypes.arrayOf(PropTypes.shape({
                field: PropTypes.string,
                enum: PropTypes.string
            }))
        }),
        uiSchema: PropTypes.object
    }).isRequired,
    schema: PropTypes.shape({
        type: PropTypes.oneOf(["object"])
    }).isRequired,
    formData: PropTypes.object
};
GeocoderField.contextType = ReactContext_1.default;
exports.default = GeocoderField;
