"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 __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 contexts_1 = require("../../contexts/index.js");
const react_1 = __importStar(require("react"));
const react_hook_form_1 = require("react-hook-form");
const react_i18next_1 = require("react-i18next");
const EnhancedPhoneNumberField_1 = __importDefault(require("../generic/custom/EnhancedPhoneNumberField/EnhancedPhoneNumberField"));
const ForwardedSelect_1 = __importDefault(require("../generic/ForwardedSelect"));
const InputGroup_1 = __importDefault(require("../generic/InputGroup/InputGroup"));
const LargeLoader_1 = __importDefault(require("../generic/loader/LargeLoader"));
const TextBox_1 = __importDefault(require("../generic/TextBox"));
const CountryCodesAndNumbers_1 = require("../../models/CountryCodesAndNumbers");
const Translation_1 = require("../../translations/Translation");
const Validation_1 = require("../../util/Validation");
const PasswordBox_1 = require("../generic/PasswordBox/PasswordBox");
const EditMyProfile = () => {
    const { roomstayMember, loading, updateMemberDetails } = (0, react_1.useContext)(contexts_1.RoomstayMemberContext);
    const { error: cognitoError } = (0, react_1.useContext)(contexts_1.AuthenticationContext);
    const { handleSubmit, register, reset, control, formState, setError } = (0, react_hook_form_1.useForm)({
        defaultValues: (0, react_1.useMemo)(() => roomstayMember, [roomstayMember]),
    });
    const { t } = (0, react_i18next_1.useTranslation)();
    (0, react_1.useEffect)(() => {
        reset(roomstayMember);
    }, [roomstayMember, reset]);
    const onSubmit = (data) => __awaiter(void 0, void 0, void 0, function* () {
        if ((data === null || data === void 0 ? void 0 : data.currentPassword) || (data === null || data === void 0 ? void 0 : data.newPassword) || (data === null || data === void 0 ? void 0 : data.confirmPassword)) {
            if (data.newPassword !== data.confirmPassword) {
                setError('confirmPassword', { message: t(Translation_1.Translation.UserPortal.ProfileScreen.Validation.Password.DoesNotMatch) });
                return;
            }
        }
        yield (updateMemberDetails === null || updateMemberDetails === void 0 ? void 0 : updateMemberDetails(data));
        reset(Object.assign(Object.assign({}, roomstayMember), { currentPassword: '', newPassword: '', confirmPassword: '' }));
    });
    const countriesOptions = (0, react_1.useMemo)(() => {
        const countries = CountryCodesAndNumbers_1.ListOfCountriesAndCodes.map(({ label }) => ({ label, value: label }));
        countries.unshift({ label: '', value: '' });
        return countries;
    }, []);
    const getValidationClass = (field) => {
        if (formState.errors && formState.touchedFields[field]) {
            if (formState.errors[field]) {
                return 'error';
            }
            else {
                return 'success';
            }
        }
        else {
            return null;
        }
    };
    return (react_1.default.createElement(react_1.default.Fragment, null, roomstayMember ? (react_1.default.createElement("div", null,
        react_1.default.createElement("form", { onSubmit: handleSubmit(onSubmit) },
            react_1.default.createElement(InputGroup_1.default, null,
                react_1.default.createElement(react_1.default.Fragment, null,
                    react_1.default.createElement("input", { className: "c-input textbox", disabled: true, value: roomstayMember === null || roomstayMember === void 0 ? void 0 : roomstayMember.email })),
                react_1.default.createElement(TextBox_1.default, Object.assign({}, register('forename'), { label: t(Translation_1.Translation.UserPortal.ProfileScreen.Field.Forename) })),
                react_1.default.createElement(TextBox_1.default, Object.assign({}, register('surname'), { label: t(Translation_1.Translation.UserPortal.ProfileScreen.Field.Surname) })),
                react_1.default.createElement(react_1.default.Fragment, null,
                    react_1.default.createElement(react_hook_form_1.Controller, { control: control, name: "phoneNumber", rules: {
                            maxLength: {
                                value: 17,
                                message: t(Translation_1.Translation.UserPortal.ProfileScreen.Validation.Phone.IsTooLong),
                            },
                            pattern: {
                                value: /^\+[1-9]( |\d){1,15}$/g,
                                message: t(Translation_1.Translation.UserPortal.ProfileScreen.Validation.Phone.IsNotValid),
                            },
                        }, render: ({ field }) => react_1.default.createElement(EnhancedPhoneNumberField_1.default, Object.assign({}, field, { onChange: field.onChange, validationStatus: getValidationClass('phoneNumber') })) }))),
            react_1.default.createElement(InputGroup_1.default, null,
                react_1.default.createElement(TextBox_1.default, Object.assign({}, register('address.address'), { label: t(Translation_1.Translation.UserPortal.ProfileScreen.Field.Address) })),
                react_1.default.createElement(TextBox_1.default, Object.assign({}, register('address.city'), { label: t(Translation_1.Translation.UserPortal.ProfileScreen.Field.City) })),
                react_1.default.createElement(InputGroup_1.default, { dimensions: "2/2" },
                    react_1.default.createElement(TextBox_1.default, Object.assign({ inputProps: { className: '' } }, register('address.zip'), { label: t(Translation_1.Translation.UserPortal.ProfileScreen.Field.Zip) })),
                    react_1.default.createElement(ForwardedSelect_1.default, Object.assign({}, register('address.country'), { options: countriesOptions, label: t(Translation_1.Translation.UserPortal.ProfileScreen.Field.Country) })))),
            react_1.default.createElement(InputGroup_1.default, null,
                react_1.default.createElement(PasswordBox_1.PasswordBox, Object.assign({}, register('currentPassword'), { label: t(Translation_1.Translation.UserPortal.ChangePassword.Field.CurrentPassword) })),
                react_1.default.createElement(PasswordBox_1.PasswordBox, Object.assign({}, register('newPassword', {
                    pattern: (0, Validation_1.makePasswordPatternRule)(t),
                }), { label: t(Translation_1.Translation.UserPortal.ChangePassword.Field.NewPassword) })),
                react_1.default.createElement(PasswordBox_1.PasswordBox, Object.assign({}, register('confirmPassword', {
                    pattern: (0, Validation_1.makePasswordPatternRule)(t),
                }), { label: t(Translation_1.Translation.UserPortal.ChangePassword.Field.ConfirmPassword) })),
                cognitoError && (react_1.default.createElement("p", { className: "text-small", style: { color: '#ED4362' } }, cognitoError === null || cognitoError === void 0 ? void 0 : cognitoError.message))),
            react_1.default.createElement("button", { type: "submit", disabled: loading, color: "primary" }, t(Translation_1.Translation.Misc.SaveAllChanges))))) : (react_1.default.createElement(LargeLoader_1.default, null))));
};
exports.default = EditMyProfile;
//# sourceMappingURL=EditMyProfile.js.map