/* FichothequeLib_Tools - Copyright (c) 2013-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;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import net.fichotheque.utils.AddendaUtils;
import net.mapeadores.util.text.FileName;
import net.mapeadores.util.text.StringUtils;


/**
 *
 * @author Vincent Calame
 */
public class DocumentChangeInfo {

    public final static DocumentChangeInfo EMPTY = new DocumentChangeInfo();
    private final List<FileName> tmpFileNameList = new ArrayList<FileName>();
    private final List<String> removedExtensionList = new ArrayList<String>();
    private String newBasename;

    private DocumentChangeInfo() {
    }

    public String getNewBasename() {
        return newBasename;
    }

    public int getTmpFileCount() {
        return tmpFileNameList.size();
    }

    public FileName getTmpFileName(int i) {
        return tmpFileNameList.get(i);
    }

    public int getRemovedExtensionCount() {
        return removedExtensionList.size();
    }

    public String getRemovedExtension(int i) {
        return removedExtensionList.get(i);
    }

    public static DocumentChangeInfo parse(String s) {
        String[] params = StringUtils.getTokens(s, ',', StringUtils.EMPTY_EXCLUDE);
        DocumentChangeInfo documentChangeInfo = new DocumentChangeInfo();
        int length = params.length;
        for (int i = 0; i < length; i++) {
            String[] couple = StringUtils.getTokens(params[i], '=', StringUtils.EMPTY_EXCLUDE);
            if (couple.length != 2) {
                continue;
            }
            String key = couple[0];
            String value = couple[1];
            if (key.equals("bn")) {
                documentChangeInfo.newBasename = value;
            } else if (key.equals("tf")) {
                FileName fileName = parseTmpFileName(value);
                if (fileName != null) {
                    documentChangeInfo.tmpFileNameList.add(fileName);
                }
            } else if (key.equals("re")) {

                documentChangeInfo.removedExtensionList.add(value);
            }
        }
        return documentChangeInfo;
    }

    public static FileName parseTmpFileName(String s) {
        FileName fileName;
        try {
            fileName = FileName.parse(s);
        } catch (ParseException pe) {
            return null;
        }
        if (!AddendaUtils.testExtension(fileName.getExtension())) {
            return null;
        }
        return fileName;
    }

}
