import { tryCatch, always } from 'ramda';
import { whenDefined } from '@devprotocol/util-ts';
import { decode } from '@devprotocol/clubs-core';

var SlotName;
(function (SlotName) {
    SlotName["PostsEditAfterContentForm"] = "posts:edit:after:content-form";
    SlotName["PostsFeedAfterPostContent"] = "posts:feed:after:post-content";
})(SlotName || (SlotName = {}));
var Event;
(function (Event) {
    Event["PostCreated"] = "posts:event::post_created";
    Event["RegisterOnUpdateHandler"] = "posts:event::register_on_update_handler";
})(Event || (Event = {}));

/* eslint-disable @typescript-eslint/prefer-readonly-parameter-types */
/* eslint-disable functional/no-expression-statement */
/* eslint-disable functional/no-let */
/* eslint-disable functional/no-return-void */
/* eslint-disable functional/no-loop-statement */
const onUpdateHandlers = new Set();
const handleRegisterOnUpdateHandler = (e) => {
    return typeof e.detail.handler === 'function'
        ? onUpdateHandlers.add(e.detail.handler)
        : onUpdateHandlers;
};
// eslint-disable-next-line functional/no-return-void
const onUpdate = (handler) => typeof document !== 'undefined' &&
    document.dispatchEvent(new CustomEvent(Event.RegisterOnUpdateHandler, { detail: { handler } }));
const update = async (_post) => {
    // eslint-disable-next-line functional/no-let
    let post = _post;
    for await (const handler of onUpdateHandlers) {
        post = await tryCatch(handler, always(post))(post);
    }
    return post;
};
const EncodedPostClassName = '__input-encoded-post__';
const currentPost = (handler, base) => {
    let current = base;
    let input;
    let count = 0;
    while (count < 30 && !input) {
        input = current?.getElementsByClassName(EncodedPostClassName)?.[0];
        current = current?.parentElement;
        count = count + 1;
    }
    whenDefined(input, (_input) => {
        handler(decode(_input.value));
        new MutationObserver((mutationList) => {
            console.log({ mutationList });
            mutationList.some(({ attributeName }) => attributeName === 'value') &&
                handler(decode(_input.value));
        }).observe(_input, { attributes: true });
        return _input;
    });
    return input;
};
const onPostCreated = (handler) => typeof document !== 'undefined' &&
    document.addEventListener(Event.PostCreated, (e) => handler(e.detail.post));
// eslint-disable-next-line functional/no-return-void
const dispatchPostCreated = (post) => typeof document !== 'undefined' &&
    document.dispatchEvent(new CustomEvent(Event.PostCreated, { detail: { post } }));

export { EncodedPostClassName, currentPost, dispatchPostCreated, handleRegisterOnUpdateHandler, onPostCreated, onUpdate, onUpdateHandlers, update };
