/* global window */
import 'can-define-stream';
import canStream from 'can-stream';
import DefineMap from 'can-define/map/';
import route from 'can-route';
// import 'can-route-pushstate';
import Session from 'bitcentive/models/session';
// import 'bitcentive/models/fixtures/';

// viewmodel debugging
import viewModel from 'can-view-model';
window.viewModel = viewModel;

var pages = {
  home: 'public',
  dashboard: 'private',
  contributors: 'private'
};

const AppViewModel = DefineMap.extend({

  /**
   * By default, viewModel attributes will not be serialized into the URL as
   * route attributes.
   */
  '*': {
    serialize: false
  },

  /**
   * Use Session.get() to see if there's a valid JWT. If one exists, 
   * a new Session will be created.
   */
  session: {
    stream (setStream) {
      Session.get().catch(err => console.log(err));
      return canStream.toStream(Session, 'created')
        .merge(canStream.toStream(Session, 'destroyed'))
        .map(event => event.type === 'created' ? event.args[0] : undefined);
    }
  },

  /**
   * Determines which page-level component is displayed.
   */
  page: {
    serialize: true,
    get (page, setPage) {
      if (page === 'logout') {
        return this.logout();
      }

      if (pages[page]) {
        // Logic for authenticated users.
        if (this.session) {
          if (page === 'home') {
            page = 'dashboard';
          }
        // Logic for non-authenticated users.
        } else {
          if (pages[page] !== 'public') {
            page = 'home';
          }
        }
      // 404 if the page isn't in the list of pages.
      } else {
        page = 'four-oh-four';
      }
      return page;
    }
  },

  /**
   * The `title` attribute is used in index.stache as the HTML title.
   */
  title: {
    value: 'Bitcentive'
  },

  logout () {
    this.session && this.session.destroy()
      .then(() => {
        if (!window.doneSsr) {
          this.page = 'home';
        }
      });
  }
});

route('{page}', {page: 'home'});

export default AppViewModel;

@@ -638,30 +638,347 @@
 false%0A  %7D,%0A%0A
+  // Once https://github.com/canjs/can-define-stream/issues/15 is fixed, %0A  // we can move the initialSession into the session %60value%60 function.%0A  initialSession: %7B%0A    value () %7B%0A      Session.get().then(session =%3E %7B%0A        this.initialSession = session;%0A      %7D)%0A      .catch(err =%3E console.log(err));%0A    %7D%0A  %7D,%0A%0A
   /**%0A
-
    * Use Ses
@@ -1086,24 +1086,44 @@
  session: %7B%0A
+    // value () %7B%7D,%0A
     stream (
@@ -1139,60 +1139,8 @@
 ) %7B%0A
-      Session.get().catch(err =%3E console.log(err));%0A
     
@@ -1281,18 +1281,20 @@
 ype 
-=
+!
 == '
-creat
+destroy
 ed' 
@@ -1321,16 +1321,63 @@
 defined)
+%0A        .merge(this.stream('.initialSession'))
 ;%0A    %7D%0A

Set initial session in its own property.