import { AnimationConfig } from 'lottie-web';
import { GetRewardsCommand } from '../commands/rewardAnimations/getRewardsCommand';
import { RewardAnimation } from '../models/rewardAnimations/rewardAnimation';
import { BaseService } from './abstract/baseService';
import dataService from './dataService';
import localStorageService from './localStorageService';

class AnimationService extends BaseService {
    public static sharedInstance = new AnimationService();

    protected logTag: string = 'AnimationService';

    public getAnimationConfiguration(animationName: string, pointsAwarded: string): AnimationConfig | null {
        const animation = this.loadAnimationWithName(animationName);
        if (!animation) {
            return null;
        } else {
            let jsonDescription = animation.jsonDescription;
            jsonDescription = this.injectDynamicText(jsonDescription, pointsAwarded);
            const animationConfig: AnimationConfig = {
                animationData: JSON.parse(jsonDescription),
                autoplay: false,
                loop: false,
                renderer: 'svg',
            };
            return animationConfig;
        }
    }

    public async getAnimations(): Promise<RewardAnimation[] | null> {
        if (localStorageService.animations && localStorageService.animations.length) {
            return localStorageService.animations;
        }

        const getAnimationsCommand = new GetRewardsCommand();
        const rewards = await dataService.executeCommand(getAnimationsCommand);
        if (!rewards) {
            return null;
        } else {
            localStorageService.animations = rewards;
            return rewards;
        }
    }

    public loadAnimationWithName(animationName: string): RewardAnimation | null {
        const storedAnimations = localStorageService.animations;
        if (!storedAnimations) {
            this.logError('No stored animation info to display found. Not rendering animation.');
            return null;
        } else {
            const animation = storedAnimations.filter((a) => {
                return a.name === animationName;
            });

            if (!animation || !animation.length) {
                this.logError(`No animation with name ${animationName} found. Not rendering animation.`);
                return null;
            }

            return animation[0];
        }
    }

    private injectDynamicText(baseJson: string, pointsAwarded: string): string {
        if (pointsAwarded) {
            baseJson = baseJson.replace(/"20"/gi, `\"${pointsAwarded}\"`);
        }
        return baseJson;
    }
}

export default AnimationService.sharedInstance as AnimationService;