import Reflux from 'Reflux';
import cartActions from '../actions/cartActions.js';
import _ from 'lodash';
// Items to fill onFillCart action
let items = [
  {
    title: 'Iphone 12',
    price: '129',
    id: 1
  },
  {
    title: 'Galaxy S14',
    price: '119',
    id: 2
  },
  {
    title: 'Siemens A52',
    price: '197',
    id: 3
  },
  {
    title: 'Nokia 3310',
    price: '329',
    id: 4
  }
];
// Storage keys to use when stroing
let localStorageKeys = ['cart', 'toggles'];
// Constructor for toggles object on init
let Toggles = () => {
  let obj = {
    title: false,
    price: false,
    quantity: false
  }
  return obj;
};

let cartStore = Reflux.createStore ({

  // Assign actions
  listenables: [cartActions],
  // Initial state
  getInitialState() {
    // Load from local Storage or empty array
    this.data = JSON.parse(localStorage.getItem(localStorageKeys[0])) || new Array;
    // Load from local Storage or new Toggles object
    this.toggles = JSON.parse(localStorage.getItem(localStorageKeys[1])) || new Toggles;
    // return to component state
    return {items: this.data};
  },
  // onAdd action
  onAdd(item) {
    // Update cart with item
    this.updateCart(this.addItem(item));
  },
  //onDelete action
  onDelete(item) {
    // delete item from cart
    this.updateCart(this.deleteItem(item));
  },
  onFillCart() {
    // Add each item to cart then pass to anAdd so it updates cart
    _.map(items, (item) => {this.onAdd(item)})
  },
  onSortTitle() {
    // Set other toggles states
    this.toggles.price = false;
    this.toggles.quantity = false;
    // Toggle this state
    this.toggles.title = !this.toggles.title;
    // Assign
    let toggle = this.toggles.title;
    // Update cart through sortBy()
    this.updateCart(this.sortBy(toggle, 'title'));
  },
  onSortPrice() {
    // Set other toggles states
    this.toggles.title = false;
    this.toggles.quantity = false;
    // Toggle this state
    this.toggles.price = !this.toggles.price;
    // Assign
    let toggle = this.toggles.price;
    // Update cart through sortBy()
    this.updateCart(this.sortBy(toggle, 'price'));
  },
  onSortQuantity() {
    // Set other toggles states
    this.toggles.title = false;
    this.toggles.price = false;
    // Toggle this state
    this.toggles.quantity = !this.toggles.quantity;
    // Assign
    let toggle = this.toggles.quantity;
    // Update cart through sortBy()
    this.updateCart(this.sortBy(toggle, 'quantity'));
    // ABOVE NEEDS INCAPSULATION
  },
  onSubmit() {

    // Dummy ajax post to emulate success
    $.ajax({
      url: 'http://jsonplaceholder.typicode.com/posts',
      dataType: 'json',
      type: 'POST',
      data: {data: this.data},
      success: function(data) {
        UIkit.notify({
        message : 'Success!',
        status  : 'success',
        timeout : 5000,
        pos     : 'top-center'
        });
        this.clearCart();
      }.bind(this),
      error: function(xhr, status, err) {
        UIkit.notify({
        message : 'Error! </br>' + err.toString(),
        status  : 'danger',
        timeout : 5000,
        pos     : 'top-center'
        });
        console.error(xhr, status, err.toString());
      }
    });


  },
  sortBy(toggle, key) {
    let items;
    // if not sorted
    if (toggle) {
      items = _.orderBy(this.data, key, 'asc');
    }
    // if sorted -> reverse
    if (!toggle) {
      items =  _.orderBy(this.data, key, 'desc');
    }
    // store state of toggles
    localStorage.setItem(localStorageKeys[1], JSON.stringify(this.toggles));
    return items;

  },
  updateCart(items) {
    // save items to local storage
    localStorage.setItem(localStorageKeys[0], JSON.stringify(items));
    // assign to this object
    this.data = items;
    // trigger component state change
    this.trigger({items});
  },
  addItem (item) {
    let found, i;
    found = false;
    i = 0;
    let items = this.data.concat();
    // loop through items
    while (i < items.length) 

    // if not found
    if (!found) {
      // add new item with quantity 1
      Object.assign(item, {quantity: 1});
      items.push(item);
    }
    return items;
  },
  deleteItem (item) {
    let items = this.data.concat();
    let i = items.length;
    // loop through items in reverse
    while (i--) {
      // if found item with the same id and quantity more than 1 -> decrement
      if (item.id === items[i].id && items[i].quantity > 1) {
          items[i].quantity--;
          break;

      };
      // if found item with the same id and quantity equals 1 -> remove;
      if (item.id === items[i].id && items[i].quantity === 1) {
          items.splice(i, 1);
          break;
      };
    }
    return items;
  },
  // clearing cart on successfull submit
  clearCart() {
    // clear local Storage
    _.map(localStorageKeys, (key) => {
      localStorage.removeItem(key);
    })
    let empty = new Array;
    // update cart with empty Array
    this.updateCart(empty);
  }

});

export default cartStore;

{
      // if find item with the same id
      if (item.id === items[i].id) {
        // increment quantity
        items[i].quantity++;
        found = true;
        break;
      }
      i++;
    }