import * as React from 'react';
import * as ReactDOM from 'react-dom';
import settings from '../../config/settings';
import { AmplitudeEvents } from '../../events/amplitudeEvents';
import { RewardCardShownEvent } from '../../models/amplitude/RewardCardShownEvent';
import { RewardAnimation } from '../../models/rewardAnimations/rewardAnimation';
import { Reward } from '../../models/tasks/reward';
import { TaskType } from '../../models/tasks/taskType';
import animationService from '../../services/animationService';
import eventEmitter from '../../services/eventEmitter';
import { PresentableView } from '../abstract/presentableView';
import { AnimationRewardCard } from './animationRewardCard';

export class RewardCardView extends PresentableView {
    protected logTag: string = 'RewardCardView';
    private injectedElem: HTMLElement;

    constructor(private task: TaskType, private reward: Reward) {
        super();
    }

    public async presentSelf(onStartCallback?: () => void): Promise<boolean> {
        return new Promise<boolean>(async (resolve) => {
            const animation = await animationService.loadAnimationWithName(this.reward.animationName);
            if (animation) {
                this.injectedElem = document.createElement('div');
                document.body.appendChild(this.injectedElem);
                await this.renderCardWithAnimation(animation, resolve, onStartCallback);
            }
        });
    }

    private async renderCardWithAnimation(animation: RewardAnimation, resolve: (value?: boolean) => void, onStartCallback?: () => void) {
        if (animation.jsonDescription) {
            this.notifyRewardCardShown();
            ReactDOM.render(
                <AnimationRewardCard
                    reward={this.reward}
                    animation={animation}
                    onStart={onStartCallback}
                    onFinish={() => this.dismissAndResolve(resolve)}
                />
                , this.injectedElem);
        } else if (animation.videoUrl) {
            const videoRewardCard = await import (/* webpackChunkName: 'nonstop-home' */ './videoRewardCard');
            this.notifyRewardCardShown();
            ReactDOM.render(
                <videoRewardCard.VideoRewardCard
                    reward={this.reward}
                    animation={animation}
                    onFinish={() => this.dismissAndResolve(resolve)}
                />
            , this.injectedElem);
        } else {
            this.dismissAndResolve(resolve);
        }
    }

    private async dismissAndResolve(resolve: (value?: boolean) => void) {
        await this.dismissSelf(this.injectedElem, settings.animateCssAnimationDurationMs);
        resolve(true);
    }

    private notifyRewardCardShown() {
        eventEmitter.broadcastEvent(AmplitudeEvents.RewardCardShown, new RewardCardShownEvent(this.reward.pointsAwarded, this.task));
    }

}