import _Message from "./_Message.js";
import isUndefined from './util/isUndefined.js';
import isArray from './util/isArray.js';
import Home from './Home.js';
import _Cart from './_Cart.js';
import _DB from './_DB.js';
import _Navigation from './_Navigation.js';


var _User = {};

_User.guest = {tier: 'silver'};
_User.current = _User.guest;

_User.session_hash = null;

_User.isGold = function(){
  return _User.current.tier === 'gold';
  }

_User.isLoggedIn = function(){
  return !(_User.current === _User.guest);
  };

_User.isGuest = function(){
  return (_User.current === _User.guest);
  };

_User.isAdmin = function(){
  return (_User.current.is_admin);
  };

_User.attemptLogin = function(username, password){
  m.request({
    method: 'POST',
    url: '/cgi/attemptlogin', 
    body: { username: username, password: password }
    })
  .then(function(res){
    if(res.success === true){
      var user = res.user;
      _User.current = user;
      _User.session_hash = res.session_hash;
      _Message.addNotification("Welcome, "+user.firstname+"!");
      
      if(!isArray(res.cart.lineitem_ids)){
        res.cart.lineitem_ids = [];
        }
      res.cart.lineitem_ids.forEach(function(lineitem, index){
        lineitem.item_id = _DB.integrate(lineitem.item_id).id;
        res.cart.lineitem_ids[index] = _DB.integrate(lineitem).id;
        });
      _Cart.current = _DB.integrate(res.cart);
      
      return _Cart.current;
      }
    else{
      _Message.addError("Wrong Username/Password!");
      //return false;
      }
    });
  };

_User.logout = function(){
  m.request({
    method: 'POST',
    url: '/cgi/logout', 
    body: { session_hash: _User.session_hash }
    })
  .then(function(res){
    if(res.success === true){
      _User.current = _User.guest;
      _User.session_hash = null;
      _Cart.current = null;
      _Message.addNotification("Logged out!");
      _Navigation.component = Home;
      _Navigation.attrs = null;
      }
    else{
      _Message.addError("Couldn't log out for some reason...");
      }
    });
  };

export default _User;