import { BlazePlayerType } from '../interfaces';
import { BlazeGlobalEvents } from '../shared/BlazeGlobalEvents';

export interface BlazeFollowEntity {
    id: string;
}

export interface BlazeFollowEntityClickedParams {
    sourceId: string;
    playerType: BlazePlayerType;
    newFollowingState: boolean;
    followEntity: BlazeFollowEntity;
}

export interface BlazeFollowEntitiesDelegate {
    onFollowEntityClicked?: (params: BlazeFollowEntityClickedParams) => void;
}

export class BlazeFollowEntitiesDelegateHelper {

    static registerFollowEntitiesDelegate(delegate?: BlazeFollowEntitiesDelegate | null) {
        BlazeFollowEntitiesDelegateHelper.onFollowEntityClicked(delegate?.onFollowEntityClicked)
    }

    private static onFollowEntityClicked(
        callback?: (params: BlazeFollowEntityClickedParams) => void,
    ) {
        const eventName = 'Blaze.onFollowEntityClicked'
        if (callback) {
            BlazeGlobalEvents.createEventSubscription(
                eventName,
                (data: any) => {
                    try {
                        const playerType = data['playerType'] as BlazePlayerType;
                        const sourceId = data['sourceId'];
                        const newFollowingState = data['newFollowingState'];
                        const followEntity: BlazeFollowEntity = {
                            id: data['followEntityId']
                        };
                        callback({
                            playerType,
                            sourceId,
                            newFollowingState,
                            followEntity
                        });
                    } catch (e) {
                        console.error('BlazeFollowEntitiesDelegateHelper.onFollowEntityClicked', e);
                    }
                },
            );
        } else {
            BlazeGlobalEvents.cancelEventSubscription(eventName)
        }
    }
}