package com.evilco.mc.nbt.tag;

import com.evilco.mc.nbt.stream.NbtInputStream;
import com.evilco.mc.nbt.stream.NbtOutputStream;
import com.google.common.base.Preconditions;
import java.io.IOException;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;

public abstract class AbstractTag implements ITag {
   protected String name;
   protected ITagContainer parent = null;

   public AbstractTag(@Nonnull String name) {
      this.setName(name);
   }

   public AbstractTag(@Nonnull NbtInputStream inputStream, boolean anonymous) throws IOException {
      Preconditions.checkNotNull(inputStream, "inputStream");
      if (!anonymous) {
         int nameSize = inputStream.readShort();
         byte[] nameBytes = new byte[nameSize];
         inputStream.readFully(nameBytes);
         this.setName(new String(nameBytes, STRING_CHARSET));
      }

   }

   public String getName() {
      return this.name;
   }

   public byte[] getNameBytes() {
      return this.name.getBytes(STRING_CHARSET);
   }

   public ITagContainer getParent() {
      return this.parent;
   }

   public abstract byte getTagID();

   public void setName(@Nonnull String name) {
      Preconditions.checkNotNull(name, "name");
      if (this.getParent() != null) {
         this.getParent().removeTag(this);
      }

      this.name = name;
      if (this.getParent() != null) {
         if (this.getParent() instanceof IAnonymousTagContainer) {
            ((IAnonymousTagContainer)this.getParent()).addTag(this);
         } else {
            ((INamedTagContainer)this.getParent()).setTag(this);
         }
      }

   }

   public void setParent(@Nullable ITagContainer parent) {
      if (this.getParent() != null) {
         this.getParent().removeTag(this);
      }

      this.parent = parent;
   }

   public void write(NbtOutputStream outputStream, boolean anonymous) throws IOException {
      if (!anonymous) {
         byte[] name = this.getNameBytes();
         outputStream.writeShort(name.length);
         outputStream.write(name);
      }

   }
}
