--- /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.io.File;
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.imageio.ImageIO;
+
+import org.hedgecode.chess.img.AbstractImageLoader;
+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 File PIECES_PATH = new File(IMAGES_PATH, 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 = null;
+ if (Type.STATELESS.equals(loadType()) || !pieceSetMap.containsKey(name)) {
+ File piecePath = new File(PIECES_PATH, name);
+ if (piecePath.exists() && piecePath.isDirectory()) {
+ 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(File piecePath) throws ImageException {
+ PieceSet pieceSet = PieceSet.create();
+ File[] images = piecePath.listFiles(new ImageFilter(PIECES_NAMES));
+ if (images != null) {
+ for (File image : images) {
+ if (image.isFile()) {
+ String filename = image.getName();
+ try {
+ pieceSet.add(
+ filename.substring(0, filename.lastIndexOf('.')),
+ ImageIO.read(image)
+ );
+ } catch (IOException e) {
+ throw new ImageException(e.getMessage()); // todo: locale
+ }
+ }
+ }
+ }
+ return pieceSet.isFull() ? pieceSet : null;
+ }
+
+}