/* 
 * Define singleton NotificationService
 */
angular
    .module('NotificationService', [])
    .service('PushNotification', ['notifyStatus', '$rootScope', 'notifyCode', function (notifyStatus, $rootScope, notifyCode) {
            // Define Socket object
            var socket = {
                client: null,
                channel: null,
                callback: null,
                callbackSystemNotify: null,
                isPlaySound: false,
                client_id: null,
                team_id: null,
                project_id: null,
                type: null
            };

            var audio = null;
            var isInitialize = false;
            var isConnected = false;

            function subscribeProjectPush() {
                socket.pusher.bind("notify-topic-event", function (message) {
                    var result = JSON.parse(message);
                    if (result) {
                        //finish copied project
                        if (result.code === notifyCode.COPY_PROJECT.code) {
                            $rootScope.$broadcast("copy_project_success_notify", result);
                        }

                        if (!result.clientId || result.clientId !== socket.client_id) {
                            socket.callback && socket.callback(result, result.projectId, function () {
                                // Play a sound
                                if (socket.isPlaySound) {
                                    try {
                                        if (audio === null)
                                            // Play sound notify
                                            audio = new Audio('https://cdn.livechatinc.com/sounds/message.ogg');
                                        if (result.code === 100 || result.code === 101) {

                                            audio.play();
                                        }

                                    } catch (e) {
                                    } finally {
                                        $rootScope.$broadcast("new_notify", result);
                                    }
                                }
                            });
                        }
                    }
                });
            }

            function subscribeSystemPush() {
                socket.pusher.bind("notify-system-event", function (messageSystemNotify) {
                    var result = JSON.parse(messageSystemNotify);
                    if (result) {
                        if (!result.clientId || result.clientId !== socket.client_id) {
                            socket.callbackSystemNotify(result);
                        }
                    }
                });
            }

            function initializeSocket() {
                if (!isInitialize) {
                    subscribeProjectPush();
                    subscribeSystemPush();
                    isInitialize = true;
                }
            }

            function createConnection() {
                if (isConnected)
                    return socket;
                else {
                    var pusher = new Pusher('3fb93ad214349785bf8d', {
                        cluster: 'ap1',
                        encrypted: true
                    });
                    socket.pusher = pusher.subscribe(socket.team_id);
                    // socket.pusher = pusher.subscribe('notify-channel');
                    isConnected = true;
                    return socket;
                }
            }

            function notifyDesktop(result) {
                if (!Notification) {
                    alert('Desktop notifications not available in your browser. Try Chromium.');
                    return;
                }
                if (Notification.permission !== "granted") {
                    Notification.requestPermission();
                } else {

                    var text = unescape(result.text.replace(/\\u([\d\w]{4})/gi, function (match, grp) {
                        return String.fromCharCode(parseInt(grp, 16));
                    }));
                    var notification = new Notification('Notify', {
                        icon: 'img/689Cloud_small.png',
                        body: text,
                        dir: "ltr"
                    });

                    notification.onclick = function () {
                        window.open("#/project/" + result.projectId);
                    };
                }
            }

            return {
                // Websocket project notification
                initializeSocketNotification: function (callbackFunction, session, isPlaySound) {
                    socket.callback = callbackFunction;
                    socket.type = notifyStatus.NOTIFICATION;
                    socket.isPlaySound = isPlaySound;
                    socket.client_id = session.getToken();
                    socket.team_id = session.getUser().team_id;
                    socket = createConnection();
                    initializeSocket();
                },
                // Websocket system  notification
                initializeSocketSystemNotification: function (callbackFunction, option) {
                    socket.type = notifyStatus.SYSTEM_NOTIFY;
                    socket.callbackSystemNotify = callbackFunction;
                    socket.client_id = option.token;
                    socket.team_id = option.team_id;
                    socket.project_id = option.project_id;
                    socket = createConnection();
                    initializeSocket();
                }
            };

        }]
    );
