<commit_before>'use strict';

import Promise from 'bluebird';
import Reflux from 'reflux';
import Actions from '../actions/Actions';
import { firebaseUrl } from '../util/constants';

import Firebase from 'firebase';

const baseRef = new Firebase(firebaseUrl);
const usersRef = baseRef.child('users');

const defaultUser = {
    uid: '',
    profile: {
        username: '',
        upvoted: {}
    },
    isLoggedIn: false
};

// copy defaultUser to currentUser
let currentUser = Object.assign({}, defaultUser);

const UserStore = Reflux.createStore({

    listenables: Actions,

    init() {
        // triggered by auth changes
        baseRef.onAuth(function(authData) {
            if (!authData) {
                // user is logged out
                usersRef.off();
                this.logoutCompleted();
            } else {
                // user is logged in
                this.loginCompleted(authData.uid);
            }
        }.bind(this));
    },

    logout() {
        baseRef.unauth();
    },

    logoutCompleted() {
        // reset currentUser to default
        currentUser = Object.assign({}, defaultUser);
        this.trigger(currentUser);
    },

    loginCompleted(userId) {
        // watch their profile for updates
        usersRef.child(userId).on('value', profile => (
            this.updateProfile(userId, profile.val())
        ));
    },

    updateProfile(userId, newProfile) {
        currentUser = Object.assign({}, {
            uid: userId,
            profile: newProfile,
            isLoggedIn: true
        });

        this.trigger(currentUser);
    },

    getUserId(username) {
        // returns userId given username
        return new Promise(function(resolve) {
            usersRef.orderByChild('username').equalTo(username).once('value', function(user) {
                let userId = Object.keys(user.val())[0];
                resolve(userId);
            });<commit_msg>flatten user data, make UserStore immutable<commit_after>'use strict';

import React from 'react/addons';
import Reflux from 'reflux';
import Actions from '../actions/Actions';
import { firebaseUrl } from '../util/constants';

import Firebase from 'firebase';
const baseRef = new Firebase(firebaseUrl);
const usersRef = baseRef.child('users');

const update = React.addons.update;

const defaultUser = {
    uid: '',
    username: '',
    upvoted: null,
    submitted: null,
    isLoggedIn: false,
    md5hash: null,
    latestPost: null
};

let currentUser = Object.assign({}, defaultUser);

const UserStore = Reflux.createStore({

    listenables: Actions,

    init() {
        // triggered by auth changes
        baseRef.onAuth((authData) => {
            if (!authData) {
                // user is logged out
                usersRef.off();
                this.logoutCompleted();
            } else {
                // user is logged in
                this.loginCompleted(authData.uid);
            }
        });
    },

    logout() {
        baseRef.unauth();
    },

    logoutCompleted() {
        // reset currentUser to default
        currentUser = Object.assign({}, defaultUser);
        this.trigger(currentUser);
    },

    loginCompleted(userId) {
        // get username
        usersRef.child(userId).once('value', (profile) => {
            let {
                username,
                upvoted,
                submitted,
                md5hash
            } = profile.val();

            currentUser = {
                uid: userId,
                username: username,
                upvoted: upvoted,
                submitted: submitted || null,
                md5hash: md5hash,
                isLoggedIn: true,
                latestPost: null
            };

            // watch upvotes
            usersRef.child(`${userId}/upvoted`).on('value', (upvoted) => {
                this.updateUpvoted(upvoted.val());
            });

            // watch submissions
            usersRef.child(`${userId}/submitted`).on('value', (submitted) => {
                let submittedVal = submitted.val();
                this.updateSubmitted(submittedVal ? Object.keys(submittedVal) : []);
            });
        });
    },

    updateLatestPost(postId) {
        currentUser = update(currentUser, {
            latestPost: { $set: postId }
        });

        this.trigger(currentUser);
    },

    updateUpvoted(newUpvoted) {
        currentUser = update(currentUser, {
            upvoted: { $set: newUpvoted }
        });

        this.trigger(currentUser);
    },

    updateSubmitted(newSubmitted) {
        currentUser = update(currentUser, {
            submitted: { $set: newSubmitted || null }
        });

        this.trigger(currentUser);
    },

    getUserId(username) {
        // returns userId given username
        return new Promise((resolve) => {
            usersRef.orderByChild('username').equalTo(username).once('value', (user) => {
                let userId = Object.keys(user.val())[0];
                resolve(userId);
            });
{'fraction_non_alphanumeric': 0.1248258013139558, 'fraction_numerical': 0.0011945052757316346, 'mean_word_length': 1.8082727780883174, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 10, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4410082', 'n_tokens_mistral': 1389, 'n_tokens_neox': 1345, 'n_words': 285}