const Action = function(fn) {
  this.fn = fn;
  this.execute = this.execute.bind(this);
};
Action.prototype = {
  execute: function() {
    this.fn.apply(this, arguments);
  }
};
const ACTION = {
  NAVIGATE: new Action((where, data, silent)=>{

    store.set({
      'navigation.current': where,
      'navigation.data': data || {}
    });
    if(!silent){
      Model.history.push( { current: where, data: data || {} } );
      //debugger
      history.pushState( { place: where, data: data || {} }, '', Page[ where ].route.generate( data || {} ) );
    }
  }),
  NAVIGATE_BACK: new Action(()=>{
    store.set('navigation', Model.history.pop());
  }),

  CARD: {
    LEARN_MORE: new Action((item)=>{
      ACTION.NAVIGATE.execute('InfoPage', {id: item.id, category: item.category_id});
    })
  },
  YOU_CAN: {
    START_TEST_TESTING: new Action(()=>{
      console.log('START_TEST_TESTING');
      ACTION.NAVIGATE.execute('ChooseType');
    })
  },
  TEST: {
    DEMO: {
      GOTO_FINAL_WELCOME: new Action(()=>{
        ACTION.NAVIGATE.execute('WelcomeDemoFinal');
      }),
      GOTO_FINAL_LAST_NOTIFICATION: new Action(()=>{
        ACTION.NAVIGATE.execute('WelcomeDemoFinalLastNotification');
      }),
      GOTO_FINAL_TEST: new Action(()=>{
        ACTION.NAVIGATE.execute('DemoTesting');
      }),
      LIMITLESS: new Action(()=>{

      })
    }
  },

  Action
};

export default ACTION
export {ACTION};
if(typeof window !== 'undefined'){
  window.ACTION = ACTION;
  window.onpopstate = function(event) {
    store.set({
      'navigation.current': event.state.place,
      'navigation.data': event.state.data || {}
    });
  };
  const path = document.location.pathname;
  tmpStore.valEqualOnly('loaded', true)(function() {
    //debugger
    let bestMatch = Object.values(Page)
      .map((page)=>({page, match: page.route.match(path)}))
      .sort((a,b)=>b.match - a.match)
      [0];
    console.log('ROUTE:', bestMatch.page.route.pageName)
    if(bestMatch.match<0.1){
      // 404
      store.set({
        'navigation.current': '404',
        'navigation.data': {url: path}
      });
    }else{
      bestMatch.page.route.load(path)
    }

  });
}
