/* FichothequeLib_Tools - Copyright (c) 2007-2020 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 net.fichotheque.tools.parsers.ficheblock;

import java.text.ParseException;
import net.fichotheque.SubsetKey;
import net.fichotheque.corpus.fiche.Atts;
import net.fichotheque.corpus.fiche.Insert;
import net.fichotheque.tools.parsers.TextContentParser;
import net.fichotheque.utils.FicheUtils;
import net.mapeadores.util.text.StringUtils;


/**
 *
 * @author Vincent Calame
 */
class InsertParser extends BlockParser {

    private final TextContentParser textContentParser;

    InsertParser(TextContentParser textContentParser) {
        this.textContentParser = textContentParser;
    }

    @Override
    public boolean isStartLine(String line) {
        return line.startsWith(":::");
    }

    @Override
    public void parse(String[] lineArray, int startIndex, Atts initAtts) {
        String firstLine = StringUtils.cleanString(lineArray[startIndex]);
        short type = Insert.IMAGE_TYPE;
        short position = Insert.POSITION_UNDETERMINED;
        if (firstLine.length() > 3) {
            String params = firstLine.substring(3).trim();
            if (params.length() > 0) {
                type = Insert.typeToShort(params.charAt(0));
                if (type == Insert.LETTRINE_TYPE) {
                    if (params.length() > 1) {
                        position = Insert.positionToShort(params.charAt(1));
                    }
                }
            }
        }
        Insert insert = new Insert(type);
        FicheUtils.populate(insert, initAtts);
        insert.setPosition(position);
        int stop = lineArray.length - 1;
        for (int i = startIndex + 1; i <= stop; i++) {
            String line = StringUtils.cleanString(lineArray[i]);
            if (line.startsWith(":::")) {
                stop = i;
                break;
            } else {
                if (line.length() > 0) {
                    parseLine(insert, line);
                }
            }
        }
        setParseResult(stop, insert);
    }

    private void parseLine(Insert insert, String line) {
        int idx = line.indexOf('=');
        if (idx == -1) {
            return;
        }
        String txt = line.substring(idx + 1).trim();
        char carac = line.charAt(0);
        switch (carac) {
            case 'i':
                if (Insert.isIllustrationType(insert.getType())) {
                    boolean illustrationDone = parseIllustration(insert, txt);
                    if (!illustrationDone) {
                        if (insert.getSrc().length() == 0) {
                            insert.setSrc(txt);
                        }
                    }
                }
                break;
            case 'd':
                boolean documentDone = parseDocument(insert, txt);
                if (!documentDone) {
                    if (insert.getSrc().length() == 0) {
                        insert.setSrc(txt);
                    }
                }
                break;
            case 's':
                insert.setSrc(txt);
                break;
            case 'r':
                insert.setRef(txt);
                break;
            case 'w':
                try {
                int width = Integer.parseInt(txt);
                insert.setWidth(width);
            } catch (NumberFormatException nfe) {
            }
            break;
            case 'h':
                try {
                int height = Integer.parseInt(txt);
                insert.setHeight(height);
            } catch (NumberFormatException nfe) {
            }
            break;
            case 'l':
                textContentParser.parse(insert.getLegendeBuilder(), txt);
                break;
            case 'n':
                textContentParser.parse(insert.getNumeroBuilder(), txt);
                break;
            case 'a':
                textContentParser.parse(insert.getAltBuilder(), txt);
                break;
            case 'c':
                textContentParser.parse(insert.getCreditBuilder(), txt);
                break;
        }
    }

    private boolean parseIllustration(Insert insert, String txt) {
        int idx = txt.indexOf('/');
        if (idx < 1) {
            return false;
        }
        try {
            SubsetKey albumKey = SubsetKey.parse(SubsetKey.CATEGORY_ALBUM, txt.substring(0, idx));
            int id = Integer.parseInt(txt.substring(idx + 1));
            insert.setSubsetItem(albumKey, id, "");
            return true;
        } catch (ParseException | NumberFormatException e) {
            return false;
        }
    }

    private boolean parseDocument(Insert insert, String txt) {
        int idx = txt.indexOf('/');
        if (idx < 1) {
            return false;
        }
        try {
            SubsetKey addendaKey = SubsetKey.parse(SubsetKey.CATEGORY_ADDENDA, txt.substring(0, idx));
            int id = Integer.parseInt(txt.substring(idx + 1));
            insert.setSubsetItem(addendaKey, id, "");
            return true;
        } catch (ParseException | NumberFormatException e) {
            return false;
        }
    }

}
