"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 (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __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 });
exports.Lottie = void 0;
const react_1 = __importStar(require("react"));
const react_intersection_observer_1 = require("react-intersection-observer");
const lottie_web_1 = __importDefault(require("lottie-web"));
const hooks_1 = require("../../hooks");
const uuid_util_1 = require("../../utils/uuid.util");
const IconWithImage_1 = require("../IconWithImage");
const Styled = __importStar(require("./index.styled"));
const Lottie = ({ width, height, viewBox, className, playOnce, autoplay = false, alterImgSrcOnLoad, lottieFileSrcPath: lottieFileName, }) => {
    const [animationData, setAnimationData] = (0, react_1.useState)(null);
    const rootElement = (0, react_1.useRef)(null);
    const elementId = (0, react_1.useRef)((0, uuid_util_1.uuid)());
    const isMobile = (0, hooks_1.useLayoutIsMobile)();
    const { ref: wrapperRef, inView } = (0, react_intersection_observer_1.useInView)({
        /**
         * 모바일 : 로띠의 높이가 PC와 다르게 작기 때문에 스크롤시 로띠의 play 시작점을 자연스럽게 하기위해 0.4
         * PC : 로띠의 play 시작점이 lottie 끝에 들어왔을때 play하기 위해 value 0.9
         */
        threshold: isMobile ? 0.4 : 0.9,
        /**
         * rootMargin을 주어서 lottie inview에 대한 범위를 추가하였습니다.
         * 모바일, PC의 높이가 달라 다르게 선언하였습니다.
         */
        rootMargin: isMobile ? '20% 0% 0% 0%' : '40% 0% 10% 0%',
    });
    const viewBoxSize = (0, react_1.useMemo)(() => { var _a, _b; return (viewBox ? `${(_a = viewBox.x) !== null && _a !== void 0 ? _a : 0} ${(_b = viewBox.y) !== null && _b !== void 0 ? _b : 0} ${viewBox.width} ${viewBox.height}` : undefined); }, [viewBox]);
    const [lottieInstance, setLottieInstance] = (0, react_1.useState)();
    (0, react_1.useEffect)(() => {
        fetch(lottieFileName)
            .then((res) => res.json())
            .then((data) => {
            setAnimationData(data);
        })
            .catch(() => {
            console.info('lottie load 에 실패했습니다.');
        });
    }, [lottieFileName]);
    (0, react_1.useEffect)(() => {
        if (!rootElement.current || !animationData) {
            return;
        }
        const lottieInstance = lottie_web_1.default.loadAnimation({
            container: rootElement.current,
            renderer: 'svg',
            loop: !Boolean(playOnce),
            autoplay,
            animationData,
            rendererSettings: {
                viewBoxSize,
            },
            name: className,
        });
        setLottieInstance(lottieInstance);
        return () => lottie_web_1.default.destroy(lottieInstance.name);
    }, [animationData, className, autoplay, playOnce, viewBoxSize]);
    (0, react_1.useEffect)(() => {
        if (inView) {
            lottieInstance === null || lottieInstance === void 0 ? void 0 : lottieInstance.goToAndPlay((lottieInstance === null || lottieInstance === void 0 ? void 0 : lottieInstance.currentFrame) > 0.9 * (lottieInstance === null || lottieInstance === void 0 ? void 0 : lottieInstance.totalFrames) ? 0 : lottieInstance === null || lottieInstance === void 0 ? void 0 : lottieInstance.currentFrame, true);
        }
        else {
            if (playOnce) {
                lottieInstance === null || lottieInstance === void 0 ? void 0 : lottieInstance.stop();
            }
            else {
                lottieInstance === null || lottieInstance === void 0 ? void 0 : lottieInstance.pause();
            }
        }
    }, [inView, lottieInstance, playOnce]);
    if (animationData === null && alterImgSrcOnLoad) {
        return (react_1.default.createElement(Styled.AlterImageWrapper, null,
            react_1.default.createElement(IconWithImage_1.IconWithImage, { width: width || 0, srcPath: alterImgSrcOnLoad })));
    }
    return (react_1.default.createElement(Styled.Wrapper, { ref: wrapperRef },
        react_1.default.createElement(Styled.Container, { id: elementId.current, className: className, ref: rootElement, width: width, height: height })));
};
exports.Lottie = Lottie;
