import { Platform } from "react-native";
import { CometChat } from "@cometchat/chat-sdk-react-native";
import { CometChatUIKitHelper } from "./CometChatUIKitHelper";
import { messageStatus } from "../utils/CometChatMessageHelper";
import { CallingExtension } from "../../calls/CallingExtension";
import { CallingPackage } from "../../calls/CallingPackage";
import { StickersExtension } from "../../extensions/Stickers";
import { CollaborativeWhiteboardExtension } from "../../extensions/CollaborativeWhiteboard/CollaborativeWhiteboardExtension";
import { LinkPreviewExtention } from "../../extensions/LinkPreview";
import { CollaborativeDocumentExtension } from "../../extensions/CollaborativeDocument/CollaborativeDocumentExtension";
import { PollsExtension } from "../../extensions/Polls/PollsExtension";
import { SmartRepliesExtension } from "../../extensions/SmartReplies";
import { ChatConfigurator } from "../framework";
import { ImageModerationExtension } from "../../extensions/ImageModeration";
import { MessageTranslationExtension } from "../../extensions/MessageTranslation";
import { TextModerationExtension } from "../../extensions/TextModeration";
import { ThumbnailGenerationExtension } from "../../extensions/ThumbnailGeneration";
import { CometChatSoundManager } from "../utils";
import { CometChatLocalize } from "../resources";
import { ListenerInitializer } from "../events/ListenerInitializer";
import { AIConversationStarterExtension } from "../../AI/AIConversationStarter/AIConversationStarter";
import { AISmartRepliesExtension } from "../../AI/AISmartReplies/AISmartReplies";
import { AIConversationSummaryExtension } from "../../AI/AIConversationSummary/AIConversationSummaryExtension";
import { AIAssistBotExtension } from "../../AI/AIAssistBot/AIAssistBotExtension";
import { permissionUtil } from "../utils/PermissionUtil";
import { getUnixTimestamp, } from '../../shared/utils/CometChatMessageHelper';
export class CometChatUIKit {
    static uiKitSettings;
    static aiFeatures;
    static loggedInUser = null;
    static loginListenerID = ``;
    static isLoginListenerAttached = false;
    static init(uiKitSettings) {
        //perform sdk init taking values from uiKitSettings
        CometChatUIKit.uiKitSettings = {
            ...uiKitSettings
        };
        var appSetting = new CometChat.AppSettingsBuilder()
            .subscribePresenceForAllUsers()
            .autoEstablishSocketConnection(uiKitSettings.autoEstablishSocketConnection)
            .overrideAdminHost(uiKitSettings?.overrideAdminHost)
            .overrideClientHost(uiKitSettings?.overrideClientHost)
            .setRegion(uiKitSettings.region);
        appSetting.subscriptionType = uiKitSettings.subscriptionType;
        CometChatUIKit.attachListener();
        return CometChat.init(uiKitSettings.appId, appSetting.build()).then(() => {
            CometChat.setSource("uikit-v4", Platform.OS, "react-native");
            ListenerInitializer.attachListeners();
            CometChat.getLoggedinUser()
                .then(user => {
                console.log("setting logged in user", user);
                CometChatUIKit.setLoggedInUser(user);
                if (user) {
                    this.enableExtensions();
                }
            })
                .catch(error => {
                // CometChatUIKit.setLoggedInUser(null);
            });
            permissionUtil.init().then(res => {
                if (res !== true) {
                    console.warn("[IOS] Permission initialization failed.");
                }
            });
        }, error => {
            // console.log("Initialization failed with error:", error);
        });
    }
    static defaultExtensions = [
        new StickersExtension(),
        new SmartRepliesExtension(),
        new CollaborativeWhiteboardExtension(),
        new CollaborativeDocumentExtension(),
        new MessageTranslationExtension(),
        new TextModerationExtension(),
        new ThumbnailGenerationExtension(),
        new LinkPreviewExtention(),
        new PollsExtension(),
        new ImageModerationExtension()
    ];
    static defaultAIFeatures = [
        new AISmartRepliesExtension(),
        new AIConversationStarterExtension(),
        new AIConversationSummaryExtension(),
        new AIAssistBotExtension()
    ];
    static attachListener() {
        if (CometChatUIKit.isLoginListenerAttached) {
            CometChatUIKit.removeListener();
            CometChatUIKit.isLoginListenerAttached = false;
            CometChatUIKit.loginListenerID = ``;
        }
        CometChatUIKit.loginListenerID = `__CometChatLoginListener__`;
        CometChat.addLoginListener(CometChatUIKit.loginListenerID, new CometChat.LoginListener({
            onLoggedIn: (user) => {
                CometChatUIKit.setLoggedInUser(user);
            },
            onLoggedOut: () => {
                CometChatUIKit.removeLoggedInUser();
            },
        }));
        CometChatUIKit.isLoginListenerAttached = true;
    }
    static enableExtensions() {
        ChatConfigurator.init(); //re-initialize data source
        if (!CometChatUIKit.uiKitSettings.disableCalling) {
            if (CallingPackage.isCallingPackageInstalled)
                new CallingExtension().enable();
        }
        let extensionList = this.uiKitSettings?.extensions || this.defaultExtensions;
        let aiFeaturesList = this.uiKitSettings?.aiFeatures || this.defaultAIFeatures;
        if (extensionList.length > 0) {
            extensionList.forEach((extension) => {
                extension?.enable();
            });
        }
        if (aiFeaturesList.length > 0) {
            aiFeaturesList.forEach((aiFeatures) => {
                aiFeatures.enable();
            });
        }
    }
    static async getLoggedInUser() {
        if (CometChatUIKit.checkAuthSettings(Promise.reject))
            null;
        let user = await CometChat.getLoggedinUser().catch((e) => Promise.reject(e));
        if (user == null) {
            throw (new CometChat.CometChatException({ code: "NOT_FOUND", message: "Login user not found" }));
        }
        else {
            this.enableExtensions();
        }
        return user;
    }
    static setLoggedInUser(user) {
        this.loggedInUser = user;
    }
    static removeLoggedInUser() {
        this.loggedInUser = null;
    }
    static removeListener() {
        if (CometChatUIKit.isLoginListenerAttached) {
            CometChat.removeLoginListener(CometChatUIKit.loginListenerID);
            CometChatUIKit.isLoginListenerAttached = false;
            CometChatUIKit.loginListenerID = ``;
        }
    }
    static async login({ uid, authToken }) {
        if (CometChatUIKit.checkAuthSettings(Promise.reject))
            null;
        if (uid) {
            let user = await CometChat.login(uid, CometChatUIKit.uiKitSettings?.authKey).catch(e => Promise.reject(e));
            CometChatUIKit.setLoggedInUser(user);
            this.enableExtensions();
            return user;
        }
        if (authToken) {
            let user = await CometChat.login(authToken).catch(e => Promise.reject(e));
            this.enableExtensions();
            return user;
        }
        return Promise.reject(new CometChat.CometChatException({ code: "INVALID_LOGIN_ATTEMPT", message: "Provide uid or authToken" }));
    }
    static logout() {
        if (this.checkAuthSettings(Promise.reject)) { }
        return CometChat.logout();
    }
    static createUser(user) {
        if (this.checkAuthSettings(Promise.reject)) { }
        return CometChat.createUser(user, this.uiKitSettings.authKey);
    }
    static updateUser(user) {
        if (this.checkAuthSettings(Promise.reject)) { }
        return CometChat.updateUser(user, this.uiKitSettings.authKey);
    }
    //Error handling to give better logs
    static checkAuthSettings(onError) {
        if (this.uiKitSettings == null) {
            if (onError != null) {
                onError(new CometChat.CometChatException({
                    code: "ERR", name: "Authentication null",
                    message: "Populate authSettings before initializing"
                }));
            }
            return false;
        }
        if (!this.uiKitSettings?.appId) {
            if (onError != null) {
                onError(new CometChat.CometChatException({
                    code: "appIdErr", name: "APP ID null",
                    message: "Populate appId in authSettings before initializing"
                }));
            }
            return false;
        }
        return true;
    }
    //---------- Helper methods to send messages ----------
    ///[sendCustomMessage] used to send a custom message
    static sendCustomMessage(message) {
        return new Promise((resolve, reject) => {
            if (!message.getMuid()) {
                message.setMuid(String(getUnixTimestamp()));
            }
            if (!message.getSender()) {
                message.setSender(this.loggedInUser);
            }
            CometChatUIKitHelper.onMessageSent(message, messageStatus.inprogress);
            CometChat.sendCustomMessage(message)
                .then(customMessage => {
                CometChatUIKitHelper.onMessageSent(customMessage, messageStatus.success);
                resolve(customMessage);
            })
                .catch(err => {
                if (message.data)
                    message.data.metaData = { ...(message.data.metaData ? message.data.metaData : {}), error: true };
                CometChatUIKitHelper.onMessageSent(message, messageStatus.error);
                reject(err);
            });
        });
    }
    ///[sendMediaMessage] used to send a media message
    static sendMediaMessage(message) {
        return new Promise((resolve, reject) => {
            if (!message.getMuid()) {
                message.setMuid(String(getUnixTimestamp()));
            }
            if (!message.getSender()) {
                message.setSender(this.loggedInUser);
            }
            let hasAttachment;
            try {
                hasAttachment = message.getAttachment();
            }
            catch (error) {
                console.log("no attachment found");
            }
            if (hasAttachment == undefined) {
                let file = message['files'][0];
                if (file == undefined) {
                    reject(new CometChat.CometChatException({
                        code: "Invalid Media message object",
                        message: "file object not found."
                    }));
                }
                let attachmentObject = new CometChat.Attachment(file);
                attachmentObject.setName(file['name']);
                attachmentObject.setExtension((file['name'].lastIndexOf('.') + 1).toString());
                attachmentObject.setMimeType(file['type']);
                attachmentObject.setSize(0);
                attachmentObject.setUrl(file['uri']);
                message.setAttachment(attachmentObject);
            }
            CometChatUIKitHelper.onMessageSent(message, messageStatus.inprogress);
            CometChat.sendMediaMessage(message)
                .then(mediaMessage => {
                CometChatUIKitHelper.onMessageSent(mediaMessage, messageStatus.success);
                resolve(mediaMessage);
            })
                .catch(err => {
                if (message.data)
                    message.data.metaData = { ...(message.data.metaData ? message.data.metaData : {}), error: true };
                CometChatUIKitHelper.onMessageSent(message, messageStatus.error);
                reject(err);
            });
        });
    }
    ///[sendTextMessage] used to send a text message
    static sendTextMessage(message) {
        return new Promise((resolve, reject) => {
            if (!message?.getMuid()) {
                message.setMuid(String(getUnixTimestamp()));
            }
            if (!message?.getSender()) {
                message.setSender(this.loggedInUser);
            }
            CometChatUIKitHelper.onMessageSent(message, messageStatus.inprogress);
            CometChat.sendMessage(message)
                .then(textMessage => {
                CometChatUIKitHelper.onMessageSent(textMessage, messageStatus.success);
                resolve(textMessage);
            })
                .catch(err => {
                if (message.data)
                    message.data.metaData = { ...(message.data.metaData ? message.data.metaData : {}), error: true };
                CometChatUIKitHelper.onMessageSent(message, messageStatus.error);
                reject(err);
            });
        });
    }
    /**
   * Sends a Scheduler message and emits events based on the message status.
   * @param message - The Scheduler message to be sent.
   * @param disableLocalEvents - A boolean indicating whether to disable local events or not. Default value is false.
   */
    static sendSchedulerMessage(message, disableLocalEvents = false) {
        return new Promise((resolve, reject) => {
            if (!message.getMuid()) {
                message.setMuid(String(getUnixTimestamp()));
            }
            if (!message.getSender()) {
                message.setSender(this.loggedInUser);
            }
            if (!disableLocalEvents) {
                CometChatUIKitHelper.onMessageSent(message, messageStatus.inprogress);
            }
            CometChat.sendInteractiveMessage(message)
                .then((message) => {
                if (!disableLocalEvents) {
                    CometChatUIKitHelper.onMessageSent(message, messageStatus.success);
                }
                resolve(message);
            })
                .catch((error) => {
                console.log("error while sending message", { error });
                message.setMetadata({ error });
                // if (!disableLocalEvents) {
                //     CometChatUIKitHelper.onMessageSent(message, messageStatus.error);
                // }
                reject(error);
            });
        });
    }
    /**
   * Sends a FormMessage message and emits events based on the message status.
   * @param message - The FormMessage message to be sent.
   * @param disableLocalEvents - A boolean indicating whether to disable local events or not. Default value is false.
   */
    static sendFormMessage(message, disableLocalEvents = false) {
        return new Promise((resolve, reject) => {
            if (!message.getMuid()) {
                message.setMuid(String(getUnixTimestamp()));
            }
            if (!message.getSender()) {
                message.setSender(this.loggedInUser);
            }
            if (!disableLocalEvents) {
                CometChatUIKitHelper.onMessageSent(message, messageStatus.inprogress);
            }
            CometChat.sendInteractiveMessage(message)
                .then((message) => {
                console.log("message sent successfully", message.getSentAt());
                if (!disableLocalEvents) {
                    CometChatUIKitHelper.onMessageSent(message, messageStatus.success);
                }
                resolve(message);
            })
                .catch((error) => {
                console.log("error while sending message", { error });
                message.setMetadata({ error });
                // if (!disableLocalEvents) {
                //     CometChatUIKitHelper.onMessageSent(message, messageStatus.error);
                // }
                reject(error);
            });
        });
    }
    /**
   * Sends a Card message and emits events based on the message status.
   * @param message - The Card message to be sent.
   * @param disableLocalEvents - A boolean indicating whether to disable local events or not. Default value is false.
   */
    static sendCardMessage(message, disableLocalEvents = false) {
        return new Promise((resolve, reject) => {
            if (!message.getMuid()) {
                message.setMuid(String(getUnixTimestamp()));
            }
            if (!message.getSender()) {
                message.setSender(this.loggedInUser);
            }
            if (!disableLocalEvents) {
                CometChatUIKitHelper.onMessageSent(message, messageStatus.inprogress);
            }
            console.log("message", JSON.stringify(message));
            CometChat.sendInteractiveMessage(message)
                .then((message) => {
                console.log("message sent successfully", message.getSentAt());
                if (!disableLocalEvents) {
                    CometChatUIKitHelper.onMessageSent(message, messageStatus.success);
                }
                resolve(message);
            })
                .catch((error) => {
                console.log("error while sending message", { error });
                message.setMetadata({ error });
                // if (!disableLocalEvents) {
                //     CometChatUIKitHelper.onMessageSent(message, messageStatus.error);
                // }
                reject(error);
            });
        });
    }
    /**
   * Sends a Custom Interactive message and emits events based on the message status.
   * @param message - The Custom Interactive message to be sent.
   * @param disableLocalEvents - A boolean indicating whether to disable local events or not. Default value is false.
   */
    static sendCustomInteractiveMessage(message, disableLocalEvents = false) {
        return new Promise((resolve, reject) => {
            if (!message.getMuid()) {
                message.setMuid(String(getUnixTimestamp()));
            }
            if (!message.getSender()) {
                message.setSender(this.loggedInUser);
            }
            if (!disableLocalEvents) {
                CometChatUIKitHelper.onMessageSent(message, messageStatus.inprogress);
            }
            CometChat.sendInteractiveMessage(message)
                .then((message) => {
                console.log("message sent successfully", message.getSentAt());
                if (!disableLocalEvents) {
                    CometChatUIKitHelper.onMessageSent(message, messageStatus.success);
                }
                resolve(message);
            })
                .catch((error) => {
                console.log("error while sending message", { error });
                message.setMetadata({ error });
                // if (!disableLocalEvents) {
                //     CometChatUIKitHelper.onMessageSent(message, messageStatus.error);
                // }
                reject(error);
            });
        });
    }
    static getDataSource() {
        return ChatConfigurator.getDataSource();
    }
    static SoundManager = CometChatSoundManager;
    static Localize = CometChatLocalize;
}
//# sourceMappingURL=CometChatUIKit.js.map