/* BdfServer_Get - Copyright (c) 2009-2025 Vincent Calame - Exemole
 * Logiciel libre donné sous triple licence :
 * 1) selon les termes de la CeCILL V2
 * 2) selon les termes de l’EUPL V.1.1
 * 3) selon les termes de la GNU GPLv3
 * Voir le fichier licences.txt
 */


package fr.exemole.bdfserver.get.instructions;

import fr.exemole.bdfserver.api.BdfServer;
import fr.exemole.bdfserver.api.instruction.BdfInstruction;
import fr.exemole.bdfserver.api.instruction.BdfInstructionConstants;
import fr.exemole.bdfserver.api.users.BdfUser;
import fr.exemole.bdfserver.get.streamproducers.IllustrationStreamProducer;
import fr.exemole.bdfserver.tools.roles.PermissionSummaryBuilder;
import java.text.ParseException;
import net.fichotheque.SubsetKey;
import net.fichotheque.album.Album;
import net.fichotheque.album.AlbumConstants;
import net.fichotheque.album.Illustration;
import net.fichotheque.album.metadata.AlbumDim;
import net.fichotheque.permission.PermissionSummary;
import net.fichotheque.utils.AlbumUtils;
import net.mapeadores.util.servlets.ResponseHandler;
import net.mapeadores.util.servlets.exceptions.ForbiddenException;
import net.mapeadores.util.servlets.handlers.RedirectResponseHandler;
import net.mapeadores.util.servlets.handlers.StreamResponseHandler;


/**
 *
 * @author Vincent Calame
 */
public class IllustrationsInstruction implements BdfInstruction {

    private final BdfServer bdfServer;
    private final String filePath;

    public IllustrationsInstruction(BdfServer bdfServer, String filePath) {
        this.bdfServer = bdfServer;
        this.filePath = filePath;
    }

    @Override
    public short getBdfUserNeed() {
        return BdfInstructionConstants.MANDATORY_BDFUSER;
    }

    @Override
    public ResponseHandler runInstruction(BdfUser bdfUser) {
        int idx1 = filePath.indexOf('/');
        String dimString = null;
        String illustrationName;
        if (idx1 != -1) {
            if (filePath.indexOf('/', idx1 + 1) != -1) {
                return null;
            }
            dimString = filePath.substring(0, idx1);
            illustrationName = filePath.substring(idx1 + 1);
        } else {
            illustrationName = filePath;
        }
        int idx2 = illustrationName.indexOf('-');
        if (idx2 == -1) {
            return null;
        }
        int idx3 = illustrationName.indexOf('.');
        if (idx3 == -1) {
            return null;
        }
        if (idx3 < idx2) {
            return null;
        }
        SubsetKey albumKey;
        try {
            albumKey = SubsetKey.parse(SubsetKey.CATEGORY_ALBUM, illustrationName.substring(0, idx2));
        } catch (ParseException pe) {
            return null;
        }
        int illustrationid;
        try {
            illustrationid = Integer.parseInt(illustrationName.substring(idx2 + 1, idx3));
        } catch (NumberFormatException nfe) {
            return null;
        }
        short formatType;
        try {
            formatType = AlbumUtils.formatTypeToShort(illustrationName.substring(idx3 + 1));
        } catch (IllegalArgumentException iae) {
            return null;
        }
        Album album = (Album) bdfServer.getFichotheque().getSubset(albumKey);
        if (album == null) {
            return null;
        }
        PermissionSummary permissionSummary = PermissionSummaryBuilder.build(bdfServer, bdfUser);
        if (!permissionSummary.hasAccess(album)) {
            throw new ForbiddenException();
        }
        Illustration illustration = album.getIllustrationById(illustrationid);
        if (illustration == null) {
            return null;
        }
        AlbumDim albumDim = null;
        short specialDim = 0;
        if (dimString == null) {
            specialDim = AlbumConstants.ORIGINAL_SPECIALDIM;
        } else {
            if (dimString.equals("_mini")) {
                specialDim = AlbumConstants.MINI_SPECIALDIM;
            } else {
                albumDim = album.getAlbumMetadata().getAlbumDimByName(dimString);
                if (albumDim == null) {
                    return null;
                }
            }
        }
        if (illustration.getFormatType() != formatType) {
            return new RedirectResponseHandler(illustration.getFileName());
        }
        IllustrationStreamProducer illustrationStreamProducer;
        if (albumDim != null) {
            illustrationStreamProducer = new IllustrationStreamProducer(null, illustration, albumDim);
        } else {
            illustrationStreamProducer = new IllustrationStreamProducer(null, illustration, specialDim);
        }
        return StreamResponseHandler.init(illustrationStreamProducer);
    }

}
