var me = {};
var myAvatar = "";
//me.avatar = "https://lh6.googleusercontent.com/-lr2nyjhhjXw/AAAAAAAAAAI/AAAAAAAARmE/MdtfUmC0M4s/photo.jpg?sz=48";

var you = {};
var yourAvatar = "";
//you.avatar = "https://a11.t26.net/taringa/avatares/9/1/2/F/7/8/Demon_King1/48x48_5C5.jpg";

function startChat(you){
    resetChat();
    window.you = you;
    $("#chatWindowBox").show();
    $("#chatYouName").text(you);
}
function closeChat(){
    $("#chatYouName").text('');
    $("#chatWindowBox").hide();
    resetChat();
}

function formatAMPM(date) {
    var hours = date.getHours();
    var minutes = date.getMinutes();
    var ampm = hours >= 12 ? 'PM' : 'AM';
    hours = hours % 12;
    hours = hours ? hours : 12; // the hour '0' should be '12'
    minutes = minutes < 10 ? '0'+minutes : minutes;
    var strTime = hours + ':' + minutes + ' ' + ampm;
    return strTime;
}

//-- No use time. It is a javaScript effect.
function insertChat(who, text, time, date){
    time = time || 0;
    if (typeof date === "undefined" || date === null) {
        date = formatAMPM(new Date());
    }
    else{
        date = formatAMPM(new Date(date));
    }
    var control = "";
    var myAvatarDiv ='', youAvatarDiv = '';
    if( myAvatar != "" ) {
        myAvatarDiv = '<div class="avatar"><img class="img-circle" style="width:100%;" src="'+ me.avatar +'" /></div>';
    }
    if( yourAvatar != "" ){
        youAvatarDiv = '<div class="avatar"><img class="img-circle" style="width:100%;" src="'+ you.avatar +'" /></div>';
    }

    if (who == "you"){

        control = '<li style="width:100%">' +
            '<div class="msj macro">' +
            myAvatarDiv+
            '<div class="text text-l">' +
            '<p>'+ text +'</p>' +
            '<p><small>'+date+'</small></p>' +
            '</div>' +
            '</div>' +
            '</li>';
    }else{
        control = '<li style="width:100%;">' +
            '<div class="msj-rta macro">' +
            '<div class="text text-r">' +
            '<p>'+text+'</p>' +
            '<p><small>'+date+'</small></p>' +
            '</div>' +
            youAvatarDiv +
            '</li>';
    }
    setTimeout(
        function(){
            $("#chatInnerBox").append(control);

        }, time);

}

function resetChat(){
    $("#chatInnerBox").empty();
}

$(".mytext").on("keyup", function(e){
    if (e.which == 13){
        var text = $(this).val();
        if (text !== ""){
            FriendlyChat.prototype.saveMessage(text);
            //insertChat("me", text);
            $(this).val('');
        }
    }
});

//-- Clear Chat
resetChat();

//-- Print Messages
//insertChat("me", "Hello Tom...", 0);
//insertChat("you", "Hi, Pablo", 1500);
//insertChat("me", "What would you like to talk about today?", 3500);
//insertChat("you", "Tell me a joke",7000);
//insertChat("me", "Spaceman: Computer! Computer! Do we bring battery?!", 9500);
//insertChat("you", "LOL", 12000);


//-- NOTE: No use time on insertChat.




/*
 * ***********************************************************************
 * FIREBASE PART START
 * ********************
 * */
window.onload = function () {
    window.friendlyChat = new FriendlyChat();
};

// Initializes FriendlyChat.
function FriendlyChat() {
    this.checkSetup();

    this.initFirebase();
}

// Checks that the Firebase SDK has been correctly setup and configured.
FriendlyChat.prototype.checkSetup = function () {
    if (!window.firebase || !(firebase.app instanceof Function) || !firebase.app().options) {
        window.alert('You have not configured and imported the Firebase SDK. ' +
            'Make sure you go through the codelab setup instructions and make ' +
            'sure you are running the codelab using `firebase serve`');
    }
};

// Sets up shortcuts to Firebase features and initiate firebase auth.
FriendlyChat.prototype.initFirebase = function () {
    // Shortcuts to Firebase SDK features.
    this.auth = firebase.auth();
    this.database = firebase.database();
    this.storage = firebase.storage();
    // Initiates Firebase auth and listen to auth state changes.
    this.auth.onAuthStateChanged(this.onAuthStateChanged.bind(this));

    //Add Support Users
    //this.addAllSupports();
};

// Triggers when the auth state change for instance when the user signs-in or signs-out.
FriendlyChat.prototype.onAuthStateChanged = function (user) {
    if (user) { // User is signed in!
        console.log(user);
        me = user.email;
        //this.loadUsers();
        this.loadChatRooms();

        //this.signOut();
        // Get profile pic and user's name from the Firebase user object.
        //var profilePicUrl = user.photoURL;
        //var userName = user.displayName;

        // Set the user's profile pic and name.
        //this.userPic.style.backgroundImage = 'url(' + (profilePicUrl || '/images/profile_placeholder.png') + ')';
        //this.userName.textContent = userName;

        // Show user's profile and sign-out button.
        //this.userName.removeAttribute('hidden');
        //this.userPic.removeAttribute('hidden');
        //this.signOutButton.removeAttribute('hidden');

        // Hide sign-in button.
        //this.signInButton.setAttribute('hidden', 'true');

        // We load currently existing chant messages.
        //this.loadMessages();

        // We save the Firebase Messaging Device token and enable notifications.
        //this.saveMessagingDeviceToken();
    } else { // User is signed out!
        // Hide user's profile and sign-out button.
        //this.userName.setAttribute('hidden', 'true');
        //this.userPic.setAttribute('hidden', 'true');
        //this.signOutButton.setAttribute('hidden', 'true');

        // Show sign-in button.
        //this.signInButton.removeAttribute('hidden');
        this.signIn();
        //this.signOut();
    }
};

// Returns true if user is signed-in. Otherwise false and displays a message.
FriendlyChat.prototype.checkSignedInWithMessage = function() {
    // Return true if the user is signed in Firebase
    if (firebase.auth().currentUser) {
        return true;
    }

    // Display a message to the user using a Toast.
    var data = {
        message: 'You must sign-in first',
        timeout: 2000
    };
    console.log(data);
    return false;
};

// Saves the messaging device token to the datastore.
FriendlyChat.prototype.saveMessagingDeviceToken = function () {
    firebase.messaging().getToken().then(function (currentToken) {
        if (currentToken) {
            console.log('Got FCM device token:', currentToken);
            // Saving the Device Token to the datastore.
            firebase.database().ref('/fcmTokens').child(currentToken)
                .set(firebase.auth().currentUser.uid);
        } else {
            // Need to request permissions to show notifications.
            this.requestNotificationsPermissions();
        }
    }.bind(this)).catch(function (error) {
        console.error('Unable to get messaging token.', error);
    });
};

// Signs-in Friendly Chat.
FriendlyChat.prototype.signIn = function () {
    // Sign in Firebase using popup auth and Google as the identity provider.
    //var provider = new firebase.auth.GoogleAuthProvider();
    //this.auth.signInWithPopup(provider);


    //this.auth = firebase.auth();
    //
    //this.auth.createUser("dsadas@gmail.com", "123456", function(error, user) {
    //                if (!error) {
    //                auth.login("password", {
    //                           email: "dsadas@gmail.com",
    //                           password: "123456",
    //                           rememberMe: false
    //                           });
    //                     }
    //
    //                     });


//    this.auth.login("password", {
//               email: "dsadas@gmail.com",
//               password: "123456",
//               rememberMe: false
//               });
    this.auth.signInWithEmailAndPassword("onlinesupport3@gmail.com", "123456");
};

// Signs-out of Friendly Chat.
FriendlyChat.prototype.signOut = function () {
    // Sign out of Firebase.
    this.auth.signOut();
};


// Loads chat messages history and listens for upcoming ones.
FriendlyChat.prototype.loadChatRooms = function () {
    // Reference to the /messages/ database path.

    this.chatRooms = this.database.ref('chat_rooms');

    // Make sure we remove all previous listeners.
    this.chatRooms.off();

    var key;
    var setChatRooms = function (data) {
        var val = data.val();
        key = data.key;
        var currentUser = this.auth.currentUser;
        var currentUserUID = currentUser.uid;
        var userUID;
        //console.log(key);
        //console.log(val);
        //console.log("-------------------------");

        if (key.indexOf(currentUserUID) >= 0) {
            console.log(key);
            console.log("-------------------------");
            userUID = key.split("_" + currentUserUID);
            console.log(userUID[0]);

            return this.database.ref('/users/' + userUID[0]).once('value').then(function (snapshot) {
                var userDetails = snapshot.val();
                console.log(userDetails);
                var currentChatUsers = "<li> " +
                    "<a href='javascript:void(0)' onclick='initalizeChat(\""+userUID[0]+"\",\""+userDetails.email+"\")'> " +
                    "<i class='menu-icon fa fa-user bg-yellow'></i> " +
                    "<div class='menu-info'> " +
                    "<h4 class='control-sidebar-subheading'>" + userDetails.email + "</h4> " +
                        //"<p>New phone +1(800)555-1234</p> " +
                    "</div> " +
                    "</a> " +
                    "</li>";
                $("#recentChatMenu").append(currentChatUsers);
            });
        }

        //this.userRef = this.database.ref('users').ref(val.);

    }.bind(this);

    this.chatRooms.limitToLast(12).on('child_added', setChatRooms);
    //this.chatRooms.limitToLast(12).on('child_changed', setChatRooms);
};

function initalizeChat(key, email) {
    FriendlyChat.prototype.youUID = key;
    FriendlyChat.prototype.youEmail = email;
    startChat(email);
    FriendlyChat.prototype.initChatBoxDivs();
    FriendlyChat.prototype.loadMessages(key+"_"+firebase.auth().currentUser.uid);
}

FriendlyChat.prototype.initChatBoxDivs = function(){
    // Shortcuts to DOM Elements.
    //this.messageList = document.getElementById('messages');
    //this.messageForm = document.getElementById('message-form');
    //this.messageInput = document.getElementById('message');
    //this.submitButton = document.getElementById('submit');
    //this.submitImageButton = document.getElementById('submitImage');
    //this.imageForm = document.getElementById('image-form');
    //this.mediaCapture = document.getElementById('mediaCapture');
    //this.userPic = document.getElementById('user-pic');
    //this.userName = document.getElementById('user-name');
};

// Loads chat messages history and listens for upcoming ones.
FriendlyChat.prototype.loadMessages = function (chatRoomKey) {

    //console.log(chatRoomKey);
    // Reference to the /messages/ database path.

    var chatRooms = firebase.database().ref('chat_rooms');

    this.getMessages = chatRooms.child(chatRoomKey);

    // Make sure we remove all previous listeners.
    this.getMessages.off();

    var displayMessages = function (data) {
        console.log(data);
        var val = data.val();
        console.log(val);
        console.log("**********************");
        FriendlyChat.prototype.displayMessage(data.key, val.sender, val.senderUid, val.message, "fdgfd", "fdgdf");
    }.bind(this);

    this.getMessages.limitToLast(12).on('child_added', displayMessages);
    this.getMessages.limitToLast(12).on('child_changed', displayMessages);
};

// Displays a Message in the UI.
FriendlyChat.prototype.displayMessage = function(key, name, senderUid, text, picUrl, imageUri) {
    var myUID = firebase.auth().currentUser.uid;
    console.log(myUID);
    if(myUID == senderUid){
        insertChat('me', text, 0, key);
    }
    else{
        you = name;
        insertChat('you', text, 0, key);
    }
    $("#chatInnerBox").animate({ scrollTop: $("#chatInnerBox").height() }, 10);
};

// Saves a new message on the Firebase DB.
FriendlyChat.prototype.saveMessage = function(text) {

    // Check that the user entered a message and is signed in.
    if (text && this.checkSignedInWithMessage()) {
        var currentUser = firebase.auth().currentUser;
        // Add a new message entry to the Firebase Database.

        //console.log(currentUser);return false;
        var date = new Date(); // some mock date
        var milliseconds = date.getTime();
        this.getMessages.child(milliseconds).set({
            message:
                text,
            sender:
                currentUser.email,
            senderUid:
                currentUser.uid,
            receiver:
                this.youEmail,
            receiverUid:
                this.youUID,
            timestamp:
                milliseconds
            // photoUrl: currentUser.photoURL || '/images/profile_placeholder.png'
        })
            //this.mRef.push({
            //  message:
            //      this.messageInput.value,
            //  sender:
            //      "rashik@gmail.com",
            //  senderUid:
            //      "JgWOmZdKAnVQDlHn8KMne8dRB8U2",
            //  receiver:
            //      "soorya@gmail.com",
            //  receiverUid:
            //      "J9zHc1Ycp6VZUuNInsY5gk0Ra1H2",
            //  timestamp:
            //      milliseconds
            //  // photoUrl: currentUser.photoURL || '/images/profile_placeholder.png'
            //})
            .then(function() {

            }.bind(this)).catch(function(error) {
                console.error('Error writing new message to Firebase Database', error);
            });
    }
};







/* Support */
FriendlyChat.prototype.addAllSupports = function () {
    this.addSupport("onlinesupport1@gmail.com", "123456");
    this.addSupport("onlinesupport2@gmail.com", "123456");
    this.addSupport("onlinesupport3@gmail.com", "123456");
    this.addSupport("onlinesupport4@gmail.com", "123456");
};

FriendlyChat.prototype.addSupport = function (email, password) {
    this.auth.createUserWithEmailAndPassword(email, password).then(function (user) {
        console.log(firebase.auth().currentUser);
        var supports = firebase.database().ref('supports');
        supports.child(firebase.auth().currentUser.uid).set({
            email: firebase.auth().currentUser.email,
            firebaseToken: firebase.auth().currentUser.refreshToken,
            uid: firebase.auth().currentUser.uid
        }).then(function () {
        }.bind(this)).catch(function (error) {
            console.error('Error writing new message to Firebase Database', error);
        });
        firebase.auth().signOut();
    });
};

/* Support */


/*
 * ********************
 * FIREBASE PART END
 * *************************************************************************
 * */