001/*
002 * PlotSquared, a land and world management plugin for Minecraft.
003 * Copyright (C) IntellectualSites <https://intellectualsites.com>
004 * Copyright (C) IntellectualSites team and contributors
005 *
006 * This program is free software: you can redistribute it and/or modify
007 * it under the terms of the GNU General Public License as published by
008 * the Free Software Foundation, either version 3 of the License, or
009 * (at your option) any later version.
010 *
011 * This program is distributed in the hope that it will be useful,
012 * but WITHOUT ANY WARRANTY; without even the implied warranty of
013 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
014 * GNU General Public License for more details.
015 *
016 * You should have received a copy of the GNU General Public License
017 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
018 */
019package com.plotsquared.core.plot;
020
021import com.google.common.collect.ImmutableMap;
022import com.plotsquared.core.configuration.ConfigurationUtil;
023import com.plotsquared.core.configuration.serialization.ConfigurationSerializable;
024import com.plotsquared.core.util.BlockUtil;
025import com.plotsquared.core.util.MathMan;
026import com.plotsquared.core.util.PatternUtil;
027import com.plotsquared.core.util.StringMan;
028import com.sk89q.worldedit.function.pattern.BlockPattern;
029import com.sk89q.worldedit.function.pattern.Pattern;
030import com.sk89q.worldedit.world.block.BlockState;
031import com.sk89q.worldedit.world.block.BlockType;
032import org.checkerframework.checker.nullness.qual.NonNull;
033
034import java.util.Arrays;
035import java.util.Map;
036import java.util.Objects;
037import java.util.regex.Matcher;
038
039/**
040 * A block bucket is a container of block types, where each block
041 * has a specified chance of being randomly picked
042 */
043@SuppressWarnings({"unused", "WeakerAccess"})
044public final class BlockBucket implements ConfigurationSerializable {
045
046    private static final java.util.regex.Pattern regex = java.util.regex.Pattern.compile(
047            "((?<namespace>[A-Za-z_]+):)?(?<block>([A-Za-z_]+(\\[?[\\S\\s]+\\])?))(:(?<chance>[0-9]{1,3}))?");
048    private final StringBuilder input;
049    private boolean compiled;
050    private BlockState single;
051    private Pattern pattern;
052
053    public BlockBucket(final @NonNull BlockType type) {
054        this(type.getId());
055        this.single = type.getDefaultState();
056        this.pattern = new BlockPattern(this.single);
057        this.compiled = true;
058    }
059
060    public BlockBucket(final @NonNull BlockState state) {
061        this(state.getAsString());
062        this.single = state;
063        this.pattern = new BlockPattern(this.single);
064        this.compiled = true;
065    }
066
067    public BlockBucket(final @NonNull String input) {
068        this.input = new StringBuilder(input);
069    }
070
071    public BlockBucket() {
072        this.input = new StringBuilder();
073    }
074
075    public static BlockBucket withSingle(final @NonNull BlockState block) {
076        final BlockBucket blockBucket = new BlockBucket();
077        blockBucket.addBlock(block, 100);
078        return blockBucket;
079    }
080
081    public static BlockBucket deserialize(final @NonNull Map<String, Object> map) {
082        if (!map.containsKey("blocks")) {
083            return null;
084        }
085        return ConfigurationUtil.BLOCK_BUCKET.parseString(map.get("blocks").toString());
086    }
087
088    public void addBlock(final @NonNull BlockState block) {
089        this.addBlock(block, -1);
090    }
091
092    public void addBlock(final @NonNull BlockState block, final int chance) {
093        addBlock(block, (double) chance);
094    }
095
096    private void addBlock(final @NonNull BlockState block, double chance) {
097        if (chance == -1) {
098            chance = 1;
099        }
100        String prefix = input.length() == 0 ? "" : ",";
101        input.append(prefix).append(block).append(":").append(chance);
102        this.compiled = false;
103    }
104
105    public boolean isEmpty() {
106        return input == null || input.length() == 0;
107    }
108
109    public void compile() {
110        if (isCompiled()) {
111            return;
112        }
113        // Synchronized as BlockBuckets may require compilation asynchronously due to async chunk generation on Paper servers
114        synchronized (this) {
115            if (isCompiled()) {
116                return;
117            }
118            String string = this.input.toString();
119            if (string.isEmpty()) {
120                this.single = null;
121                this.pattern = null;
122                this.compiled = true;
123                return;
124            }
125            // Convert legacy format
126            boolean legacy = false;
127            String[] blocksStr = string.split(",(?![^\\(\\[]*[\\]\\)])");
128            if (blocksStr.length == 1) {
129                try {
130                    Matcher matcher = regex.matcher(string);
131                    if (matcher.find()) {
132                        String chanceStr = matcher.group("chance");
133                        String block = matcher.group("block");
134                        //noinspection PointlessNullCheck
135                        if (chanceStr != null && block != null && !MathMan.isInteger(block) && MathMan
136                                .isInteger(chanceStr)) {
137                            String namespace = matcher.group("namespace");
138                            string = (namespace == null ? "" : namespace + ":") + block;
139                        }
140                    }
141                    this.single = BlockUtil.get(string);
142                    this.pattern = new BlockPattern(single);
143                    this.compiled = true;
144                    return;
145                } catch (Exception ignore) {
146                }
147            }
148            for (int i = 0; i < blocksStr.length; i++) {
149                String entry = blocksStr[i];
150                Matcher matcher = regex.matcher(entry);
151                if (matcher.find()) {
152                    String chanceStr = matcher.group("chance");
153                    //noinspection PointlessNullCheck
154                    if (chanceStr != null && MathMan.isInteger(chanceStr)) {
155                        String[] parts = entry.split(":");
156                        parts = Arrays.copyOf(parts, parts.length - 1);
157                        entry = chanceStr + "%" + StringMan.join(parts, ":");
158                        blocksStr[i] = entry;
159                        legacy = true;
160                    }
161                }
162            }
163            if (legacy) {
164                string = StringMan.join(blocksStr, ",");
165            }
166            pattern = PatternUtil.parse(null, string);
167            this.compiled = true;
168        }
169    }
170
171    public boolean isCompiled() {
172        return this.compiled;
173    }
174
175    public Pattern toPattern() {
176        this.compile();
177        return this.pattern;
178    }
179
180    @Override
181    public String toString() {
182        return input.toString();
183    }
184
185    public boolean isAir() {
186        compile();
187        return isEmpty() || (single != null && single.getBlockType().getMaterial().isAir());
188    }
189
190    @Override
191    public Map<String, Object> serialize() {
192        if (!isCompiled()) {
193            compile();
194        }
195        return ImmutableMap.of("blocks", this.toString());
196    }
197
198    public boolean equals(final Object o) {
199        if (o == this) {
200            return true;
201        }
202        if (!(o instanceof final BlockBucket other)) {
203            return false;
204        }
205        final Object this$input = this.input;
206        final Object other$input = other.input;
207        return Objects.equals(this$input, other$input);
208    }
209
210    public int hashCode() {
211        final int PRIME = 59;
212        int result = 1;
213        final Object $input = this.input;
214        result = result * PRIME + ($input == null ? 43 : $input.hashCode());
215        return result;
216    }
217
218    private record Range(
219            int min,
220            int max,
221            boolean automatic
222    ) {
223
224        public int getWeight() {
225            return max - min;
226        }
227
228        public boolean isInRange(final int num) {
229            return num <= max && num >= min;
230        }
231
232    }
233
234}