Package com.kellerkindt.scs.shops

Source Code of com.kellerkindt.scs.shops.Shop

/**
* ShowCaseStandalone
* Copyright (C) 2012 Kellerkindt <copyright at kellerkindt.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.kellerkindt.scs.shops;



import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.bukkit.Chunk;
import org.bukkit.Location;
import org.bukkit.Server;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.configuration.serialization.ConfigurationSerializable;
import org.bukkit.inventory.ItemStack;

import com.kellerkindt.scs.listeners.Changeable;
import com.kellerkindt.scs.utilities.BenchMark;
import com.kellerkindt.scs.utilities.Properties;


public abstract class Shop implements ConfigurationSerializable, Changeable {
 
  // TODO
//  private static final int  maxInventoryTitleLength  = 32;
//  public static final int    DoubleChestFields    = 6*9;  // 6 rows with with 9 fields each
 
 
  // temporary variables - IMPORTANT: access via get/set !!!! // TODO remove?
  private int              lastHash    = -1;
 
  private UUID            uuid      = null;
  private Location          location    = null;
  private ItemStack          itemStack    = null;
//  private Block            block      = null;
//  private Inventory          inventory    = null;
  private boolean            isVisible    = false;
//  private int              inChest      = 0;
  private BenchMark          bench      = null;
 

//  private World            world      = null;
  private String            worldName    = null;
 
  private int             amount      = 0;
  private double             price       = 0;
  private boolean           isUnlimited   = false;
 
  private String            owner      = null;
  private List<String>        members      = new ArrayList<String>();
 

  protected Shop () {
    // for deserialization
  }
 
  /**
   * Main attributes, but there are more that have to be set!
   */
  public Shop (UUID uuid, String owner, Location location, ItemStack itemStack) {
    setUUID    (uuid);
    setOwner  (owner);
    setLocation  (location);
    setItemStack(itemStack);
  }
 
 
  /**
   * @return The Unique Shop ID
   */
  public UUID getUUID () {
    return uuid;
  }
 
  /**
   * Sets the UUID for this Shop
   * @param uuid UUID to set
   */
  public void setUUID (UUID uuid) {
    this.uuid = uuid;
  }
 
  /**
   * @param value the location of this shop
   */
  public void setLocation (Location value) {
    // can be null on creation
    if (value != null) {
      location = value;
      setWorld(value.getWorld());
    }
  }
 
  /**
   * @return The spawn point
   */
  public Location getSpawnLocation () {
    return getLocation().clone().add(0.5, 1.2, 0.5)// TODO: spawn issue?
  }
 
  /**
   * @return The block of the current location
   */
  public Block getBlock () {
    return getLocation().getBlock();
  }
 
  /**
   * @return the location where the shop is placed
   */
  public Location getLocation () {
    return location;
  }
 
  /**
   * @return the chunk where the shop is placed
   */
  public Chunk getChunk () {
    return getLocation().getChunk();
  }
 
  /**
   * @param value the world where the plugin is in
   */
  public void setWorld (World value) {
    getLocation().setWorld(value);
    setWorldName(value.getName());
  }
 
  /**
   * @return the world where the shop is placed
   */
  public World getWorld () {
    return getLocation().getWorld();
  }
 
  /**
   * Sets the world name of the world this shop is in
   * @param name Name to set
   */
  private void setWorldName (String name) {
    this.worldName = name;
  }
 
  /**
   * Needed to select a shop if the world is deleted
   * @return The name of the world
   */
  public String getWorldName () {
    return worldName;
  }
 
  /**
   * @param value the owner for this shop
   */
  public void setOwner (String value) {
    this.owner  = value;
  }
 
  /**
   * @return the owner of this shop
   */
  public String getOwner () {
    return owner;
  }
 
  /**
   * Sets the ItemStack for this shop
   * @param value  The ItemStack to set
   */
  public void setItemStack (ItemStack value) {
    this.itemStack  = value;
  }
 
  /**
   * @return The ItemStack of this shop
   */
  public ItemStack getItemStack () {
    return itemStack;
  }
 
  /**
   * @param value the amount of items
   */
  public void setAmount (int value) {
    this.amount  = value;
  }
 
  /**
   * @return the amount of items in this shop
   */
  public int getAmount () {
    return amount;
  }
 
  /**
   * @param value the price of this shop
   */
  public void setPrice (double value) {
    this.price  = value;
  }
 
  /**
   * @return the price for one item in this shop
   */
  public double getPrice () {
    return price;
  }
 
  /**
   * @param value true if the shop is unlimited, false if not
   */
  public void setUnlimited (boolean value) {
    this.isUnlimited  = value;
  }
 
  /**
   * @return true if the shop is a unlimited shop, false if not
   */
  public boolean isUnlimited () {
    return isUnlimited;
  }
 
  /**
   * Sets whether this shop is visible
   * @param value if the shop is visible, false if not
   */
  public void setVisible (boolean value) {
    this.isVisible  = value;
  }
 
  /**
   * @return true if the shop is visible, false if not
   */
  public boolean isVisible () {
    return isVisible;
  }
 

//  /**
//   * @param p
//   * @return
//   */
//  public boolean hasPermissions (Player p) {
//    return (p.getName().equalsIgnoreCase(getOwner()) || p.hasPermission(Properties.permAdmin));
//  }
// 
//  /**
//   * @return the inventory for this shop
//   */
//  public Inventory getInventory () {
//    if (inventory == null) {
//      String name  = getActivity().toString()+" "+getItemName();
//     
//      if (getItemStack().getType() == Material.WRITTEN_BOOK) {
//        name = getActivity().toString()+" "+((BookMeta)getItemStack().getItemMeta()).getTitle();//NBTInterpreter.getBookTitle(getItemStackNBT());
//      }
//     
//      if (name.length() > maxInventoryTitleLength)
//        name = name.substring(0, maxInventoryTitleLength-1);
//     
//      inventory = scs.getServer().createInventory(this, DoubleChestFields, name);
//      updateInventory();
//    }
//    return inventory;
//  }
// 
//  /**
//   * Updates the inventor
//   */
//  protected void updateInventory () {
//    getInventory().clear();
//   
//    if (getAmount() > 0)
//      inChest = ItemStackUtilities.addToInventory(getInventory(), getItemStack(), getAmount());
//    else
//      inChest = 0;
//  }
// 
//  /**
//   * When the inventory was closed
//   */
//  public void onInventoryClosed (Player player) {
//    int removed  = ItemStackUtilities.removeFromInventory(getInventory(), getCompatibleItems(), -1, needsEqualNBTTag());
//   
//    // gives the player all items back which are not compatible
//    for (ItemStack is : getInventory()) {
//      if (is != null)
//        player.getInventory().addItem(is);
//    }
//   
//    // set the new amount - after item giving back, because updateInvenotry() is called
//    setAmount(getAmount()+(removed  -inChest));
//   
//    // inform others
//    scs.callShowCaseEvent(new ShowCaseShopChangedEvent(player, this, null));
//  }
 
 
  /**
   * Starts a new benchmark if it is allowed via Properties.interactDebug
   * @param name
   */
  public void startBench (String name, String startInfo) {
    if (Properties.interactDebug) {
      bench = new  BenchMark (name);
      bench.start(startInfo);
    }
  }
 
  /**
   * Marks the BenchMark if it is allowed via Properties.interactDebug
   * @param info
   */
  public void markBench (String info) {
    if (Properties.interactDebug)
      if (bench != null)
        bench.mark(info);
  }
 
  /**
   * Marks the BenchMark if it is allowed via Properties.interactDebug
   */
  public void markBench () {
    if (Properties.interactDebug)
      if (bench != null)
        bench.mark();
  }
 
  /**
   * Stops the BenchMark
   */
  public void stopBench () {
    if (Properties.interactDebug)
      if (bench != null)
        bench.end();
  }
 

 
//  /**
//   * Sends the given player information about the shop
//   * The Sha1-key will only sent if it is not null
//   * @param player
//   * @param activity
//   * @param price
//   * @param inventory
//   * @param sha1
//   */
//  public void showDetails (Player player) {
//    String   c  = Term.COLOR_INACTIVE.get();
//   
//    // Get the color
//    if (getActivity() == Activity.SELL    && isActive())
//      c  = Term.COLOR_SELL.get();
//   
//    else if (getActivity() == Activity.BUY    && isActive())
//      c  = Term.COLOR_BUY.get();
//   
//    else if (getActivity() == Activity.EXCHANGE  && isActive())
//      c  = Term.COLOR_EXCHANGE.get();
//   
//   
//   
//    List<String>  message  = new ArrayList<String>();
//            message.add(Term.INFO_1.get() + c + getActivity().toString()   + Term.INFO_2.get() + c +scs.formatCurrency(getPrice())    + Term.INFO_9.get() + c + getOwner());
//   
//    String   text  = null;
//    String  name  = ItemStackUtilities.getDisplayName(getItemStack());//getItemName();//getItemStack().getItemMeta().getDisplayName();
//   
//    if (!isUnlimited()) {
//      if (getActivity() == Activity.BUY)
//        text = getAmount()+ "/" + getMaxAmount();
//      else
//        text = "" + getAmount();
//    } else {
//      text = Term.INFO_UNLIMITED.get();
//    }
//   
//    if (getItemStack().getType() == Material.WRITTEN_BOOK) {
//      name = ((BookMeta)getItemStack().getItemMeta()).getTitle();//NBTInterpreter.getBookTitle(getItemStackNBT());
//    }
//   
//    message.add(Term.INFO_4.get() + c + name        + Term.INFO_3.get() + c + text);
////            message.add(Term.INFO_4.get() + c + getItemName()        + Term.INFO_3.get() + c + (!isUnlimited() ? (getActivity() == Activity.BUY ? getMaxAmount() : getAmount()) : Term.INFO_UNLIMITED.get()));
//   
//    StringBuffer  buffer   = new StringBuffer();
//    String      delim  = "";
// 
////    TODO
////    for (Enchantment en : getEnchantments().keySet()) {
////      int lvl  = getEnchantments().get(en);
////     
////      buffer.append(delim + en.getName() + " lvl " + lvl);
////      delim  = ", ";
////    }
//   
//    if (buffer.toString().length() > 0)
//      message.add(Term.INFO_8.get() + c + buffer.toString());
//   
//    if (player.hasPermission(Properties.permAdmin))
//      message.add(c + getUUID());
//   
//    Messaging.mlSend(player, message);
//   
//   
//    if ((player.hasPermission(Properties.permAdmin) || isOwnerOrMember(player.getName())) && getMemberList().size() > 0)
//      Messaging.send(player, Term.INFO_16.get(getMembers()));
//  }
// 
//  /**
//   * Creates a shop for the given activity
//   * @param act
//   * @param scs
//   * @return
//   */
//  public static Shop getShop(Activity act, ShowCaseStandalone scs, int storageVersion, UUID uuid) {
//    return getShop (act, scs, new Storage(storageVersion, uuid));
//  }
// 
//  public static Shop getShop(ShowCaseStandalone scs, Storage storage) {
//    Activity  act  = Activity.getActivityFor(storage.getString(namedStringActivity));
//    return getShop(act, scs, storage);
//  }
// 
//  /**
//   * Creates a shop for the given activity and the given storage
//   * @param act
//   * @param scs
//   * @param storage
//   * @return
//   */
//  public static Shop getShop(Activity act, ShowCaseStandalone scs, Storage storage) {
//    // check activity - sometimes it gets lost!?
//    if (act == null) {
//      act = Activity.DISPLAY;
//      scs.log(Level.SEVERE, "Activity of shop is missing! Setting to Display-ShowCase");
//    }
//   
//    switch (act) {
//      case DISPLAY:
//        return new DisplayShop     (scs, storage);
//      case EXCHANGE:
//        return new ExchangeShop   (scs, storage);
//      case SELL:
//        return new SellShop      (scs, storage);
//      case BUY:
//        return new BuyShop      (scs, storage);
//      default:  // Should never happen !!
//        ShowCaseStandalone.slog(Level.SEVERE, "Couldn't encode activity="+act);
//        return null;
//    }
//  }
//
//  /**
//   * Tells the given player important information about the shop
//   * @param p
//   */
//  public abstract void info(Player p);
// 
//  /**
//   * Let the given player interact with the shop that can be buy or sale
//   * @param p
//   * @param amount
//   */
//  public abstract void interact (Player p, int interactAmount);
// 
//  /**
//   * Automatically sends the player error messages if set
//   * @return true if the player can interact with this shop, false otherwise
//   */
//  public boolean checkInteractConditions (Player p, boolean sendPlayer) {
//    if (!isVisible())
//      return false;
//   
//    if (getInventory().getViewers().size() > 0) {
//      if (sendPlayer)
//        Messaging.send(p, Term.ERROR_CURRENTLY_INVENTORY_OPENED.get());
//      return false;
//    }
//   
//    updateInventory();
//   
//    return true;
//  }

//  /**
//   * Checks if there is already an item - server-crash?
//   * If found, they will be removed
//   * @return
//   */
//  public void checkItem () {
//   
//    double     maxYDiff  = 1.5;            // max difference
//   
//    // check in this chunk, not in whole world --> faster
//    for (Entity e : getLocation().getChunk().getEntities())
//    {
//     
//      double x = e.getLocation().getX();
//      double z = e.getLocation().getZ();
//      double yDiff = getSpawnLocation().getY() - e.getLocation().getY();
//                       
//      if (yDiff < 0)
//        yDiff *= -1;
//
//      if (x == getSpawnLocation().getX() && yDiff <= maxYDiff && z == getSpawnLocation().getZ()) {
//       
//                if (e instanceof Item) {
//                  Item  item = (Item)e;
//                 
//                  // our item stack?
//                  if (ItemStackHandler.itemsEqual(item.getItemStack(), getItemStack(), false) && this.item != item)
//                    item.remove();
//                }
//               
////        try {
////          Item itemE = (Item)e;
////          if (ItemStackHandler.itemsEqual(itemE.getItemStack(), getItemStack(), false)) {
////                        ShowCaseStandalone.slog(Level.FINEST, "Existing stack: " + itemE.getItemStack().toString());
////                       
////                        if (Properties.stackToMaxAmount)
////                          itemE.getItemStack().setAmount(itemE.getItemStack().getMaxStackSize());
////                        else
////                          itemE.getItemStack().setAmount(1); //Removes duped items, which can occur.
////                       
////                        this.item.
////                       
////            this.item = itemE;
////                       
////            scs.log(Level.FINER, "Attaching to existing item.");
////            return true;
////          }
////        } catch (Exception ex) {}
//      }
//    }
//  }

 
//  /**
//   * Spawns the Item for this shop
//   * @return Item which is shown
//   */
//  public Item show () {
//    if (getSpawnLocation() == null)
//      return null;
//   
//    // check for duplicate item
//    checkItem();
//
////    if (!checkItem()) {
//   
//    // spawn new item
//    item   = getWorld().dropItem(getSpawnLocation(), getItemStack());
//    item.setVelocity(new Vector(0, 0.1, 0));
//    item.setItemStack(getItemStack());
//    item.setPickupDelay(Properties.DEFAULT_PICKUP_DELAY);  // less pickup events
//     
////    }
//    isVisible   = true;
//    return item;
//  }
//
// 
//  /**
//   * Removes the Item from this shop
//   * @return item which was removed or null
//   */
//  public Item hide () {
//    if (item != null) {      
//          Item  item  = this.item;
//         
//          // remove internal reference
//          this.item = null;
//         
//          // remove item
//          item.remove();
//         
//          int    x  = getSpawnLocation().getBlockX();
//          int   y   = 0;
//          int   z  = getSpawnLocation().getBlockZ();
//          World  w  = getSpawnLocation().getWorld();
//         
//          item.teleport(new Location(w, x, y, z));
//         
//          return item;
//    }
//    isVisible  = false;
//    return null;
//  }
 
  /**
   * @return true if the shop is active i.e. does the sell shop have stuff to sell, does the buy shop have stuff to buy ... false if not
   */
  public abstract boolean isActive ();
 
 
//  @Deprecated
//  private void setEnchantments (Map<Enchantment, Integer> enchantments) {
//    this.enchantments  = enchantments;
//    this.storage.setString(namedStringEnchantments, getEnchantmentsAsString());
//  }
//
//  @Deprecated
//  public Map<Enchantment, Integer> getEnchantments () {
//    if (enchantments == null) {
//      String  enchantments  = storage.getString(namedStringEnchantments);
//      this.enchantments    = new HashMap<Enchantment, Integer>();
//     
//      if (enchantments != null) {
//        try {
//            String ench[]    = enchantments.split(",");
//            for (String string : ench) {
//              Enchantment  enchantment  = Utilities.getEnchantmentFromString    (string);
//              int      level    = Utilities.getEnchantmentLevelFromString  (string);
//             
//              if (enchantment != null)
//                this.enchantments.put(enchantment, level);
//
//            }
//         
//        } catch (Exception e) {
//          ShowCaseStandalone.slog(Level.WARNING, "Couldn't load the enchantments for this shop("+getUSID()+"): " + e.getMessage());
//          e.printStackTrace();
//        }
//      }
//    }
//    return enchantments;
//  }


 
//  /**
//   * @param forceReset  re-set the enchantment in the storage
//   * @return the enchantments which is used by this shop
//   */
//  @Deprecated
//  public String getEnchantmentsAsString() {
//    if (storage.getString(namedStringEnchantments) == null) {
//            StringBuilder sb = new StringBuilder();
//            String delim = "";
//
//            for(Map.Entry<Enchantment, Integer> entry : getEnchantments().entrySet()) {
//                sb.append(delim);
//                sb.append(entry.getKey().getId());
//                sb.append(":");
//                sb.append(entry.getValue());
//                delim=",";
//            }
//            return sb.toString();
////            storage.setString(namedStringEnchantments, sb.toString());
//    }
//    return storage.getString(namedStringEnchantments);
//  }

//  /**
//   * Sets the NBTBase to save
//   * @param storage
//   */
//  public void setItemStackNBT (NBTTagCompound compound) {
//   
//    // nothing to do if no compound is available
//    if (compound == null) {
//      return;
//    }
//   
//    this.itemStackNBT  = compound;
//    this.storage.setString(namedStringItemStackNBT, Utilities.getStringFromNBTBase(compound));
//   
//    // remove the storage
//    storage.removeStorage(namedStorageNBT);
//   
//    // set the NBTTagCompound if a valid item stack is available
//    if (itemStack != null && itemStack instanceof CraftItemStack) {
//      ((CraftItemStack)itemStack).getHandle().setTag(compound);
//    }
//  }
 
//  /**
//   * @return The NBTStorage
//   */
//  @Deprecated
//  public NBTTagCompound getItemStackNBT () { // TODO
//    if (itemStackNBT == null) {
//     
//      // new import
//      String   stringNBT  = storage.getString  (namedStringItemStackNBT);
//      Storage  storageNBT  = storage.getStorage(namedStorageNBT);
//     
//      // new import available?
//      if (stringNBT != null) {
//       
//        // import
//        itemStackNBT  = (NBTTagCompound)Utilities.getNBTBaseFromString(stringNBT);
//      }
//     
//     
//      else {
//        // old import
//        if (storageNBT != null) {
//          itemStackNBT = new NBTStorage(storageNBT).getNBTTagCompound();
//        }
//      }
//     
//    }
//   
//    return itemStackNBT;
//  }
 
//  /**
//   * There was a version (b121) where the author, title and pages where save
//   * directly into the storage of the shop - this function removes the tags
//   * and saves the NBTTag to an extra storage in the storage of the shop
//   */
//  public void updateToNBTTagStorage () {
//    // no book saved?
//    if (storage.getBoolean("isBook") == null || storage.getBoolean("isBook") == false)
//      return;
//   
//    NBTTagCompound  tag    = new NBTTagCompound();
//    String       author  = storage.getString  ("book-author"  );
//    String      title  = storage.getString  ("book-title"  );
//    int        pages  = storage.getInteger("book-pages"  );
//    NBTTagList    list  = new NBTTagList();
//   
//    for (int i = 0; i < pages; i++) {
//      String      siteContent  = storage.getString("book-page-"+i);
//      NBTTagString  tString    = new NBTTagString(siteContent);
//     
//      tString.data  = siteContent;
//     
//      list.add(tString);
//    }
//   
//    tag.setString  ("author",   author);
//    tag.setString  ("title",  title);
//    tag.set      ("pages",   list);
//    setItemStackNBT(tag);
////    setNBTTagCompound(tag);
//  }
 
  /**
   * @return The list of all members
   */
  public List<String> getMembers() {
    return members;
  }
 
  /**
   * @param members The new list of members to set
   */
  public void setMembers (List<String> members) {
    this.members = members;
  }


//  /**
//   * Saves the current MemberList to the storage
//   */
//  private void saveMemberList () {
//    StringBuffer  members    = new StringBuffer();
//    boolean      addSplit  = false;
//   
//    for (String member : this.members) {
//      if (addSplit)
//        members.append(splitMember);
//      members.append(member);
//      addSplit = true;
//    }
//   
//    storage.setString(namedStringMembers, members.toString());
//  }
 
  /**
   * Adds a member to this shop, if
   * it isn't added yet
   * @param name  Name of the member to add
   */
  public void addMember (String name) {
    if (name != null && !getMembers().contains(name)) {
      getMembers().add(name);
    }
  }
 
  /**
   * Removes a member from this shop
   * @param name
   */
  public void removeMember (String name) {
    getMembers().remove(name);
  }
 
  /**
   * @return Whether the given player is a member of this shop 
   */
  public boolean isMember (String name) {
    return getMembers().contains(name);
  }
 
  /**
   * @return Whether the given player is the owner of this shop
   */
  public boolean isOwner (String name) {
    return getOwner().equals(name);
  }


  /**
   * Checks if the player can manage this shop
   * That means he has to be the owner or a member
   * @param sender
   * @return
   */
  public boolean isOwnerOrMember (String player) {
    if (isOwner(player) || isMember(player))
      return true;
   
    return false;
  }
 
//  /**
//   * @return A list of all ItemStacks that are compatible with
//   * the shops ItemStack
//   */
//  public List<ItemStack> getCompatibleItems () {
//    List<ItemStack>  list  = new ArrayList<ItemStack>();
//            list.add(getItemStack());
//           
//    switch (getItemStack().getType()) {
//      case WRITTEN_BOOK:
//        list.add(new ItemStack(Material.BOOK));
//        list.add(new ItemStack(Material.BOOK_AND_QUILL));
//        break;
//      default:
//        break;
//    }
//   
//    return list;
//  }
//
//
//  /**
//   * Checks if the given Material needs an
//   * equal NBTTag if it is used  in an ItemStack
//   * @param material
//   * @return
//   */
//  public boolean needsEqualNBTTag (Material material) {
//    switch (material) {
//      case WRITTEN_BOOK:
//        return false;
//       
//      case POTION:
//        return true;
//       
//      default:
//        return false;
//    }
//  }
// 
//  /**
//   * Equal to needsEqualNBTTag(getItemStack().getType())
//   * @return
//   */
//  public boolean needsEqualNBTTag () {
//    return needsEqualNBTTag(getItemStack().getType());
//  }
// 
//
//  @Override
//  public boolean onSetOwner(boolean isAdmin, boolean senderCanManage, Player sender, String owner) throws InsufficientPermissionException {
//   
//    if (isAdmin) {
//      String oldOwner = this.getOwner();
//      setOwner(owner);
//      scs.callShowCaseEvent(new ShowCaseShopChangedEvent(sender, this, oldOwner));
//      return true;
//    }
//
//    throw new InsufficientPermissionException(Term.ERROR_INSUFFICIENT_PERMISSION_SET_OWNER.get());
//  }
//
//  @Override
//  public int onGetItems(boolean isAdmin, boolean senderCanManage, Player sender, int amount) throws InsufficientPermissionException{
//   
//    if (isUnlimited())
//      throw new InsufficientPermissionException(Term.ERROR_REM_ITEMS_UNLIMITED.get());
//   
//    if (isAdmin || (senderCanManage && isOwnerOrMember(sender.getName()))) {
//      if (amount > getAmount())
//        amount = getAmount();
//     
//      amount      = ItemStackUtilities.addToInventory(sender.getInventory(), getItemStack(), amount);
//      setAmount (getAmount() - amount);
//     
//      scs.callShowCaseEvent(new ShowCaseShopChangedEvent(sender, this, null));
//      return amount;
//    }
//   
//    throw new InsufficientPermissionException(Term.ERROR_INSUFFICIENT_PERMISSION_GET_ITEM.get());
//  }
//
//  @Override
//  public int onAddItems(boolean isAdmin, boolean senderCanManage, Player sender, int amount) throws InsufficientPermissionException {
//
//    if (isUnlimited())
//      throw new InsufficientPermissionException(Term.ERROR_ADD_ITEMS_UNLIMITED.get());
//   
//    if (isAdmin || (senderCanManage && isOwnerOrMember(sender.getName()))) {
//     
//      amount = ItemStackUtilities.removeFromInventory(sender.getInventory(), getItemStack(), amount, needsEqualNBTTag());
//      setAmount (getAmount() + amount);
//     
//      scs.callShowCaseEvent(new ShowCaseShopChangedEvent(sender, this, null));
//      return amount;
//    }
//
//    throw new InsufficientPermissionException(Term.ERROR_INSUFFICIENT_PERMISSION_ADD_ITEM.get());
//  }
//
//  @Override
//  public boolean onSetPrice(boolean isAdmin, boolean senderCanManage, Player sender, double price) throws InsufficientPermissionException {
//   
//    if (isAdmin || (senderCanManage && isOwnerOrMember(sender.getName()))) {
//      setPrice(price);
//      scs.callShowCaseEvent(new ShowCaseShopChangedEvent(sender, this, null));
//      return true;
//    }
//   
//    throw new InsufficientPermissionException(Term.ERROR_INSUFFICIENT_PERMISSION_SET_PRICE.get());
//  }
//
//  @Override
//  public boolean onSetLimit(boolean isAdmin, boolean senderCanManage, Player sender, int limit) throws InsufficientPermissionException {
//   
//    if (isAdmin || (senderCanManage && isOwnerOrMember(sender.getName()))) {
//      setMaxAmount(limit);
//      scs.callShowCaseEvent(new ShowCaseShopChangedEvent(sender, this, null));
//      return true;
//    }
//   
//    throw new InsufficientPermissionException(Term.ERROR_INSUFFICIENT_PERMISSION_SET_LIMIT.get());
//  }
//
//  @Override
//  public boolean onAddMember(boolean isAdmin, boolean senderCanManage, Player sender, String member) throws InsufficientPermissionException {
//   
//    if (isAdmin || (senderCanManage && isOwner(sender.getName()))) {
//      addMember(member);
//      scs.callShowCaseEvent(new ShowCaseShopChangedEvent(sender, this, null));
//      return true;
//    }
//   
//    throw new InsufficientPermissionException(Term.ERROR_INSUFFICIENT_PERMISSION_ADD_MEMBER.get());
//  }
//
//  @Override
//  public boolean onRemMember(boolean isAdmin, boolean senderCanManage, Player sender, String member) throws InsufficientPermissionException {
//   
//    if (isAdmin || (senderCanManage && isOwner(sender.getName()))) {
//      removeMember(member);
//      scs.callShowCaseEvent(new ShowCaseShopChangedEvent(sender, this, null));
//      return true;
//    }
//   
//    throw new InsufficientPermissionException(Term.ERROR_INSUFFICIENT_PERMISSION_REM_MEMBER.get());
//  }
//
//  @Override
//  public boolean onSeeInfo(boolean isAdmin, boolean senderCanUse, Player sender) throws InsufficientPermissionException {
//   
//    if (isAdmin || senderCanUse) {
//      info(sender);
//      return true;
//    }
//   
//    throw new InsufficientPermissionException(Term.ERROR_INSUFFICIENT_PERMISSION.get());
//  }
//
//  @Override
//  public boolean onInteract(boolean isAdmin, boolean senderCanUse, Player sender, int amount) throws InsufficientPermissionException {
//   
//    if (isOwnerOrMember(sender.getName()) && !isUnlimited()) {
//      // TODO: check if this makes any problems !!!!
//      sender.openInventory(getInventory());
//      return true;
//    }
//   
//    if (senderCanUse) {
//      interact(sender, amount);
//      scs.callShowCaseEvent(new ShowCaseShopChangedEvent(sender, this, null));
//      return true;
//    }
//   
//    throw new InsufficientPermissionException(Term.ERROR_INSUFFICIENT_PERMISSION.get());
//  }
// 
//
// 
//   
//    public void msgOwner(Player player, String msg){
//        if(player != null)
//            if(!ShowCaseStandalone.pv.ignoreMessages(player))
//                Messaging.send(player, msg);
//    }
   
    // TOOD move it up
  public static final String KEY_UUID      = "uuid";
  public static final String KEY_AMOUNT    = "amount";
  public static final String KEY_PRICE    = "price";
  public static final String KEY_UNLIMITED  = "unlimited";
  public static final String KEY_ITEMSTACK  = "itemstack";
  public static final String KEY_OWNER    = "owner";
  public static final String KEY_MEMBERS    = "members";
 
  public static final String KEY_WORLD    = "world";
 
  public static final String KEY_LOCATION    = "location";
 

    /**
     * @see org.bukkit.configuration.serialization.ConfigurationSerializable#serialize()
     */
    @Override
    public Map<String, Object> serialize() {
      Map<String, Object> map = new HashMap<String, Object>();

      map.put(KEY_UUID,     getUUID().toString());
      map.put(KEY_AMOUNT,   getAmount());
      map.put(KEY_PRICE,     getPrice());
      map.put(KEY_UNLIMITED,   isUnlimited());
      map.put(KEY_ITEMSTACK,   getItemStack());
     
      map.put(KEY_OWNER,     getOwner());
      map.put(KEY_MEMBERS,   getMembers());
     
      map.put(KEY_WORLD,    new String[]{
          getWorld().getUID().toString(),
          getWorldName()});
     
      // fix for fail import
      map.put(KEY_LOCATION,  new Double[]{
          getLocation().getX(),
          getLocation().getY(),
          getLocation().getZ()});
     
     
     
      return map;
    }
   
   
    /**
     * Has to be invoked by a child!
     * Loads the given values into this shop
     * @param map  Map of values
     */
    @SuppressWarnings("unchecked")
  protected void deserialize (Map<String, Object> map, Server server) {
     
      setUUID    (UUID.fromString  ((String)map.get(KEY_UUID)));
      setAmount  ((Integermap.get(KEY_AMOUNT));
      setPrice  ((Doublemap.get(KEY_PRICE));
      setUnlimited((Booleanmap.get(KEY_UNLIMITED));
      setItemStack((ItemStack)map.get(KEY_ITEMSTACK));
     
      setOwner  ((String)map.get(KEY_OWNER));
      setMembers  ((List<String>)map.get(KEY_MEMBERS));
     
      // get the world instance
      List<String> list  = (List<String>)map.get(KEY_WORLD);

      World    world  = null;
     
      if (list.get(0) != null) {
        world    = server.getWorld(UUID.fromString(list.get(0)));
      }
     
      if (world != null) {
          // location needs the world...
        List<Double> loc  = (List<Double>)map.get(KEY_LOCATION);
         
        // set the location
          setLocation(new Location(world, loc.get(0), loc.get(1), loc.get(2)));
       
      } else {
        // world does not exist anymore, set the name
        // to be able to identify this shop
        setWorldName((String)map.get(list.get(1)));
      }
    }
   
    /**
     * @see com.kellerkindt.scs.listeners.Changeable#hasChanged()
     */
    @Override
    public boolean hasChanged() {
      return lastHash != hashCode();
    }
   
    /**
     * @see com.kellerkindt.scs.listeners.Changeable#resetHasChanged()
     */
    @Override
    public void resetHasChanged() {
      lastHash = hashCode();
    }
   
    @Override
    public int hashCode() {
      return    uuid       != null ? uuid.hashCode()       : 0
          +(location     != null ? location.hashCode()     : 0)
          +(itemStack    != null ? itemStack.hashCode()    : 0)
          +(isUnlimited       ? 1             : 0)
          +(worldName    != null ? worldName.hashCode()    : 0)
          +(getMembers()  != null  ? getMembers().hashCode()  : 0)
          +(int)price
          +amount
          +(owner      != null ? owner.hashCode()      : 0)
          +members.hashCode();
    }
}

TOP

Related Classes of com.kellerkindt.scs.shops.Shop

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.