# mcedit filter for finding and replacing text
# in commandblocks and on signs

# update 08.08.2013: create TAG_String for signs as well
from pymclevel import TAG_List
from pymclevel import TAG_Byte
from pymclevel import TAG_Int
from pymclevel import TAG_Compound
from pymclevel import TAG_Short
from pymclevel import TAG_Double
from pymclevel import TAG_String

displayName = "Replace Text"

inputs = (
  ("Find", "string"),
  ("Replace with", "string"),
  ("Signs", False),
  ("Command Blocks", False),
)

def perform(level, box, options):
  signs = options["Signs"]
  commandblocks = options["Command Blocks"]

  find = options["Find"]
  replace = options["Replace with"]

  for (chunk, slices, point) in level.getChunkSlices(box):
    for t in chunk.TileEntities:
      x = t["x"].value
      y = t["y"].value
      z = t["z"].value
      
      if x >= box.minx and x < box.maxx and y >= box.miny and y < box.maxy and z >= box.minz and z < box.maxz:
        if commandblocks and t["id"].value == "Control":
          newcmd = t["Command"].value.replace(find, replace)

          t["Command"] = TAG_String(newcmd)
          chunk.dirty = True
        if signs and t["id"].value == "Sign":
          line1 = t["Text1"].value.replace(find, replace)
          line2 = t["Text2"].value.replace(find, replace)
          line3 = t["Text3"].value.replace(find, replace)
          line4 = t["Text4"].value.replace(find, replace)

          t["Text1"] = TAG_String(line1)
          t["Text2"] = TAG_String(line2)
          t["Text3"] = TAG_String(line3)
          t["Text4"] = TAG_String(line4)
          chunk.dirty = True
