import { AsyncAuthAjax } from "../controller/Ajax";
import { API } from "../dict/Consts";

let latest, STORE_VERSION = 'v0.2';
const store = new Store(latest = {
  _VERSION_: STORE_VERSION,
  'navigation': {
    current: 'Login'
  },
  loaded: {
    cards: false
  },
  'account': {
    userID: 5,
    name: 'Диогроген Курославович',
    phone: '79999877414',
  }
});

try{
  var data = JSON.parse( localStorage.getItem( 'store' ) );
  if(data._VERSION_ !== store.get('_VERSION_')){
    console.warn('STORE:outdated, new state → localStorage');
    console.warn('\tSTORE:currentData #'+ store.get('_VERSION_'), store._props);
    console.warn('\tSTORE:savedData #'+ STORE_VERSION, data);
    console.warn('\tSTORE:hint → Run Store.restore() for restore saved state');
    console.warn('\tStore:hint → Run Store.update() for load latest default state');

    Store.restore = function() {
      for( var k in data ){
        if(k !== '_VERSION_'){
          store.set( k, data[ k ] );
        }
      }
    };
    Store.update = function() {
      for( var k in latest ){
        if(k !== '_VERSION_'){
          store.set( k, latest[ k ] );
        }
      }
    };
  }else{
    for( var k in data ){
      store.set( k, data[ k ] );
    }
    console.log('STORE:loaded ← localStorage', data);

  }
}catch( e ){}
store.on('change', function() {
  localStorage.setItem('store', JSON.stringify(store._props));
});

const createSavableStore = function(name) {
  const store = new Store(latest = {
    _VERSION_: STORE_VERSION
  });
  try{
    var data = JSON.parse( localStorage.getItem( name ) );
    if(data._VERSION_ === store.get('_VERSION_')){
      for( var k in data ){
        store.set( k, data[ k ] );
      }
    }
  }catch( e ){}
  let shouldSave,
    saveFn = function() {
      localStorage.setItem(name, JSON.stringify(store._props));
      shouldSave = false;
    };
  store.on('change', function() {
    if(!shouldSave)
      shouldSave = setTimeout(saveFn, 500);
  });
  return store;
};

const cards = createSavableStore('cards');
const categories = createSavableStore('categories');
const Model = {
  cards: cards,
  categories: categories
};

categories.loading = {};
categories.load = async function(category, cb) {
  category+='';
  if(this.get(category)){
    cb(this.get(category))
  }else if(this.loading[category]){
    this.loading[category].push(cb)
  }else{
    this.loading[category] = [cb];
    try{
      const result = await AsyncAuthAjax.get( API.ENDPOINTS.CATEGORIES_CATEGORY( category ) );
      Model.categories.set(category, result);
      this.loading[category].forEach((cb)=>cb(result));
      delete this.loading[category];
    }catch(e){

    }
  }
  if(!this.loading[category]){

  }
};

const tmpStore = new Store({
  loaded: false,
  navigation: {current: 'Login'},
  isMobile: false,
  width: window.innerWidth,
  newItemCount: 1000
});

let lastNav = null;
store.sub('navigation.current', function(val) {
  console.log('APP:navigation', lastNav,'→', val);
  lastNav = val;
});

window.store = store;
window.tmpStore = tmpStore;
window.Model = Model;