import {EventEmitter} from 'events';
import Dispatcher from './dispatcher';
import {ActionKind} from './constants';

class RepoStore extends EventEmitter {
    constructor() {
        super();
        this.unread_repos = {};
        this.current_repos = {};
        this.all_repos = {};
    }

    getAllRepos() {
        return this.all_repos;
    }

    getCurrentRepos() {
        return this.current_repos;
    }

    getUnreadRepos() {
        return this.unread_repos;
    }
}

let store = new RepoStore();
export default store;

// Use array to preseve ranking order
//
// type LangName = string;
// type RepoName = string;
// type Repository = Object;
//
// new_repos, unread_repos: Map<LangName, Map<RepoName, Repository>>
// current_repos: Map<LangName, Repository[]>

function _updateRepos(new_repos) {
    store.current_repos = new_repos;

    for (const lang in new_repos) {
        for (const repo of new_repos[lang]) {
            if (store.all_repos[lang] === undefined) {
                store.all_repos[lang] = {};
            }

            if (store.all_repos[lang][repo.full_name] === undefined) {
                if (store.current_repos[lang] === undefined) {
                    store.current_repos[lang] = {};
                }
                store.current_repos[lang][repo.full_name] = repo;
            }

            store.all_repos[lang][repo.full_name] = repo;
        }
    }

    console.log('Store Updated:');
    console.log('  unread: ' + JSON.stringify(store.unread_repos));
    console.log('  current: ' + JSON.stringify(store.current_repos));
    console.log('  all: ' + JSON.stringify(store.all_repos));
    store.emit('updated');
}

store.dispatch_token = Dispatcher.register(action => {
    switch(action.type) {
    case ActionKind.UpdateRepos: {
        _updateRepos(action.repos);
    }

    default:
        break;
    }
});


@@ -1134,31 +1134,30 @@
   if (store.
-current
+unread
 _repos%5Blang%5D
@@ -1192,39 +1192,38 @@
           store.
-current
+unread
 _repos%5Blang%5D = %7B
@@ -1263,34 +1263,42 @@
     
-store.current_repos%5Blang%5D%5B
+console.log('Added to unread: ' + 
 repo
@@ -1303,32 +1303,25 @@
 po.full_name
-%5D = repo
+)
 ;%0A          
@@ -1314,39 +1314,32 @@
 e);%0A        
-    %7D%0A%0A
         
     store.al
@@ -1322,37 +1322,36 @@
             
-    
 store.
-all
+unread
 _repos%5Blang%5D
@@ -1379,26 +1379,24 @@
 po;%0A        
-%7D%0A
     %7D%0A%0A    c
@@ -1398,238 +1398,180 @@
     
-console.log('Store Updated:');%0A    console.log('  unread: ' + JSON.stringify(store.unread_repos));%0A    console.log('  current: ' + JSON.stringify(store.current_
+        console.log('Added to all: ' + repo.full_name);%0A            store.all_repos%5Blang%5D%5Brepo.full_name%5D = 
 repo
-s))
 ;%0A    
-console.log('  all: ' + JSON.stringify(store.all_repos));
+    %7D%0A    %7D%0A%0A    // TODO: Save store to local storage%0A
 %0A   

fix updating unread repositories in store