--- /dev/null
+/*
+ * Copyright (c) 2018-2019. Developed by Hedgecode.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.hedgecode.chess.img.piece;
+
+import java.awt.image.BufferedImage;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.hedgecode.chess.img.AbstractImageLoader;
+import org.hedgecode.chess.img.FilenameUtils;
+import org.hedgecode.chess.img.ImageConstants;
+import org.hedgecode.chess.img.ImageException;
+import org.hedgecode.chess.img.ImageFilter;
+
+/**
+ *
+ *
+ * @author Dmitry Samoshin aka gotty
+ */
+public class PieceSetLoader extends AbstractImageLoader {
+
+ private static final String PIECES_DIR = ImageConstants.RESOURCE_PIECES_DIR;
+
+ private static final String[] PIECES_NAMES = PieceSet.getAllPieceNames();
+
+ private Map<String, PieceSet> pieceSetMap = new HashMap<>();
+
+ @Override
+ public PieceSet load(String name) throws ImageException {
+ PieceSet pieceSet;
+ if (Type.STATELESS.equals(loadType()) || !pieceSetMap.containsKey(name)) {
+ String piecePath = FilenameUtils.getFullPath(PIECES_DIR, name);
+ pieceSet = loadPieces(piecePath);
+ if (Type.STATEFUL.equals(loadType()) && pieceSet != null) {
+ pieceSetMap.put(name, pieceSet);
+ }
+ } else {
+ pieceSet = pieceSetMap.get(name);
+ }
+ return pieceSet;
+ }
+
+ @Override
+ public void unload(String name) {
+ if (Type.STATEFUL.equals(loadType()) && pieceSetMap.containsKey(name)) {
+ pieceSetMap.remove(name);
+ }
+ }
+
+ @Override
+ protected void clear() {
+ pieceSetMap.clear();
+ }
+
+ private PieceSet loadPieces(String piecePath) throws ImageException {
+ PieceSet pieceSet = PieceSet.create();
+ Map<String, BufferedImage> images =
+ loadImages(
+ piecePath,
+ new ImageFilter(PIECES_NAMES)
+ );
+ for (String name : PIECES_NAMES) {
+ pieceSet.add(
+ name,
+ images.get(name)
+ );
+ }
+ return pieceSet.isFull()
+ ? pieceSet
+ : null; // todo: ImageException
+ }
+
+}