var APIURL = 'https://1dhhcnzmxi.execute-api.us-east-1.amazonaws.com/v1';
var HEADERS = {'Accept': 'application/json', 'Content-Type': 'application/json'};
var USER_URL = 'https://s3.amazonaws.com/constellational-store';
var POST_URL = 'https://d2nxl7qthm5fu1.cloudfront.net';

var SettingStore = require('../stores/SettingStore');
var AppDispatcher = require('../dispatcher/AppDispatcher');
var EventEmitter = require('events').EventEmitter;
var assign = require('object-assign');
var React = require('react-native');

var {
    AsyncStorage,
} = React;


var CHANGE_EVENT = 'change';

var _posts = null;
var _postIDs = null;

function loadAsyncStore() {
  return AsyncStorage.getItem('posts').then(str => {
    _posts = JSON.parse(str);
    return AsyncStorage.getItem('postIDs').then(str => {
      _postIDs = JSON.parse(str);
      PostStore.emitChange();
    });
  });
}

function fetchUser(username) {
  return fetch(USER_URL + '/' + username).then(res => res.json());
}

function fetchPost(username, url) {
  return fetch(POST_URL + '/' + username + '/' + url).then(res => res.json());
}

function fetchFromServer() {
  var username = SettingStore.getUsername();
  return fetchUser(username).then((user) => {
    _postIDs = user.posts;
    return user.posts.map(url => fetchPost(username, url));
  }).then(Promise.all).then((posts) => {
    posts.map((post) => {
      _posts[post.id] = post;
    });
    PostStore.emitChange();
  });
} 

function updateAsyncStore() {
  return AsyncStorage.setItem('posts', JSON.stringify(_posts)).then(() => {
    if (postIDs) return AsyncStorage.setItem('postIDs', JSON.stringify(_postIDs));
  }).catch(err => {
    console.log("couldn't store post: " + err);
  });
}
   
var PostStore = assign({}, EventEmitter.prototype, {
  getAll: function() {
    if (!_postIDs) {
      loadAsyncStore().then(fetchFromServer).then(updateAsyncStore);
      return [];
    } else {
      return _postIDs.map(id => _posts[id]);
    }
  },

  emitChange: function() {
    this.emit(CHANGE_EVENT);
  },

  addChangeListener: function(callback) {
    this.on(CHANGE_EVENT, callback);
  },

  removeChangeListener: function(callback) {
    this.removeListener(CHANGE_EVENT, callback);
  }
});

AppDispatcher.register(function(action) {
  switch(action.actionType) {
    case 'create':
      var username = SettingStore.getUsername();
      var url = APIURL + '/' + username;
      action.post.token = SettingStore.getToken();
      console.log(action.post);
      var params = {method: 'POST', body: JSON.stringify(action.post), headers: HEADERS};
      fetch(url, params).then(res => res.json()).then((post) => {
        _postIDs.unshift(post.id);
        _posts[post.id] = post;
        PostStore.emitChange();
        updateAsyncStore();
      });
      break;

    case 'edit':
      var username = SettingStore.getUsername();
      action.post.token = SettingStore.getToken();
      fetch(APIURL + '/' + username, {method: 'PUT', body: JSON.stringify(action.post), HEADERS}).then(post => {
        _posts[post.id] = post;
        PostStore.emitChange();
        updateAsyncStore();
      });
      break;

    case 'delete':
      var username = SettingStore.getUsername();
      var token = SettingStore.getToken();
      var body = JSON.stringify({id: action.id, token: token});
      fetch(APIURL + '/' + username, {method: 'DELETE', body: body, HEADERS}).then(res => {
        var i = _postIDs.indexOf(action.id);
        _postIDs.splice(i, 1);
        delete _posts[action.id];
        PostStore.emitChange();
        updateAsyncStore();
      });
      break;

    case 'saveDraft':
      let post = action.post;
      if (!post.id) post.id = Date.now();
      post.isDraft = true;
      _postIDs.unshift(post.id);
      _posts[post.id] = post;
      PostStore.emitChange();
      updateAsyncStore();
      break;

  }
});

module.exports = PostStore;

@@ -604,26 +604,27 @@
 l;%0Avar _post
-ID
+URL
 s = null;%0A%0Af
@@ -770,18 +770,19 @@
 em('post
-ID
+URL
 s').then
@@ -798,26 +798,27 @@
 %0A      _post
-ID
+URL
 s = JSON.par
@@ -1221,18 +1221,19 @@
    _post
-ID
+URL
 s = user
@@ -1377,34 +1377,35 @@
     _posts%5Bpost.
-id
+url
 %5D = post;%0A    %7D)
@@ -1562,18 +1562,19 @@
 if (post
-ID
+URL
 s) retur
@@ -1601,18 +1601,19 @@
 em('post
-ID
+URL
 s', JSON
@@ -1628,18 +1628,19 @@
 fy(_post
-ID
+URL
 s));%0A  %7D
@@ -1806,18 +1806,19 @@
  (!_post
-ID
+URL
 s) %7B%0A   
@@ -1935,18 +1935,20 @@
 post
-ID
+URL
 s.map(
-id
+url
  =%3E 
@@ -1954,18 +1954,19 @@
  _posts%5B
-id
+url
 %5D);%0A    
@@ -2648,34 +2648,35 @@
  %7B%0A        _post
-ID
+URL
 s.unshift(post.i
@@ -2666,34 +2666,35 @@
 Ls.unshift(post.
-id
+url
 );%0A        _post
@@ -2692,34 +2692,35 @@
     _posts%5Bpost.
-id
+url
 %5D = post;%0A      
@@ -3039,34 +3039,35 @@
     _posts%5Bpost.
-id
+url
 %5D = post;%0A      
@@ -3288,18 +3288,19 @@
 ingify(%7B
-id
+url
 : action
@@ -3300,18 +3300,19 @@
  action.
-id
+url
 , token:
@@ -3434,18 +3434,19 @@
  = _post
-ID
+URL
 s.indexO
@@ -3454,18 +3454,19 @@
 (action.
-id
+url
 );%0A     
@@ -3473,18 +3473,19 @@
    _post
-ID
+URL
 s.splice
@@ -3521,18 +3521,19 @@
 %5Baction.
-id
+url
 %5D;%0A     
@@ -3683,19 +3683,21 @@
 ost.
-id
+url
 ) post.
-id
+url
  = D
@@ -3749,10 +3749,11 @@
 post
-ID
+URL
 s.un
@@ -3763,18 +3763,19 @@
 ft(post.
-id
+url
 );%0A     
@@ -3791,10 +3791,11 @@
 ost.
-id
+url
 %5D = 

use post urls instead of ids (for versioning)