/* FichothequeLib_API - Copyright (c) 2013-2023 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.mapeadores.util.models;

import java.text.ParseException;
import net.mapeadores.util.text.StringUtils;


/**
 *
 * @author Vincent Calame
 */
public final class EmailCoreUtils {

    private final static short VALIDE_SPEC = 2;
    private final static short HORS_SPEC = 3;
    private final static short LT = 4;
    private final static short GT = 5;

    private EmailCoreUtils() {
    }

    public static EmailCore derive(EmailCore emailCore, String realName) {
        InternalEmailCore newEmailCore = new InternalEmailCore(emailCore.getAddrSpec());
        newEmailCore.setRealName(realName);
        return newEmailCore;
    }

    public static boolean areEqual(EmailCore ec1, EmailCore ec2) {
        if (!ec1.getAddrSpec().equals(ec2.getAddrSpec())) {
            return false;
        }
        if (!ec1.getRealName().equals(ec2.getRealName())) {
            return false;
        }
        return true;
    }

    public static EmailCore parse(String s) throws ParseException {
        if (s == null) {
            throw new ParseException("s is null", 0);
        }
        s = StringUtils.cleanString(s);
        if (s.length() == 0) {
            throw new ParseException("s length is null", 0);
        }
        if (s.charAt(0) == '\"') {
            return parseWithQuote(s);
        }
        return parseWithoutQuote(s);
    }

    public static EmailCore parse(String addrSpec, String realName) throws ParseException {
        addrSpec = checkAddrspec(addrSpec.trim(), 0);
        InternalEmailCore emailCore = new InternalEmailCore(addrSpec);
        emailCore.setRealName(realName.trim());
        return emailCore;
    }

    private static EmailCore parseWithQuote(String chaine) throws ParseException {
        StringBuilder realNameBuffer = new StringBuilder();
        int departlt = 0;
        int taillechaine = chaine.length();
        boolean whitespace = false;
        for (int i = 1; i < taillechaine; i++) {
            char carac = chaine.charAt(i);
            if (Character.isWhitespace(carac)) {
                whitespace = true;
            } else if (carac == '\\') {
                if (i == taillechaine - 1) {
                    continue;
                } else {
                    if (whitespace) {
                        whitespace = false;
                        realNameBuffer.append(' ');
                    }
                    realNameBuffer.append(chaine.charAt(i + 1));
                    i++;
                }
            } else if (carac == '\"') {
                departlt = i + 1;
                break;
            } else {
                if (whitespace) {
                    whitespace = false;
                    realNameBuffer.append(' ');
                }
                realNameBuffer.append(carac);
            }
        }
        if (departlt == 0) {
            throw new ParseException("no closing quote", chaine.length() - 1);
        }
        int departaddrspec = -1;
        for (int i = departlt; i < taillechaine; i++) {
            char carac = chaine.charAt(i);
            if (carac == '<') {
                departaddrspec = i + 1;
            }
        }
        if (departaddrspec == -1) {
            throw new ParseException("no begining <", chaine.length() - 1);
        }
        String addrSpec = checkAddrspec(chaine, departaddrspec);
        InternalEmailCore emailCore = new InternalEmailCore(addrSpec);
        emailCore.setRealName(realNameBuffer.toString());
        return emailCore;
    }

    private static EmailCore parseWithoutQuote(String chaine) throws ParseException {
        int departaddrspec = chaine.indexOf('<') + 1;
        String addrSpec = checkAddrspec(chaine, departaddrspec);
        InternalEmailCore emailCore = new InternalEmailCore(addrSpec);
        if (departaddrspec > 0) {
            emailCore.setRealName(chaine.substring(0, departaddrspec - 1).trim());
        }
        return emailCore;
    }

    private static String checkAddrspec(String chaine, int depart) throws ParseException {
        StringBuilder bufaddrspec = new StringBuilder();
        int taillechaine = chaine.length();
        boolean avecarobase = false;
        for (int i = depart; i < taillechaine; i++) {
            char carac = chaine.charAt(i);
            if (Character.isISOControl(carac)) {
                continue;
            }
            if (Character.isSpaceChar(carac)) {
                continue;
            }
            if (carac == '@') {
                if (avecarobase) {
                    throw new ParseException("invalid @ character", i);
                } else {
                    if (bufaddrspec.length() == 0) {
                        throw new ParseException(chaine.substring(depart) + " starts with @ character", 0);
                    }
                    avecarobase = true;
                    bufaddrspec.append('@');
                    continue;
                }
            }
            short test = testeChar(carac);
            if (test == VALIDE_SPEC) {
                bufaddrspec.append(carac);
            } else if (test == GT) {
                if (avecarobase) {
                    return bufaddrspec.toString();
                } else {
                    throw new ParseException("closing > character without @", i);
                }
            } else {
                throw new ParseException("invalid character", i);
            }
        }
        if (avecarobase) {
            return bufaddrspec.toString();
        } else {
            throw new ParseException("missing @ character", chaine.length() - 1);
        }
    }

    private static short testeChar(char c) {
        if (c == '<') {
            return LT;
        }
        if (c == '>') {
            return GT;
        }
        if (c > '~') {
            return HORS_SPEC;
        }
        if (c == '.') {
            return VALIDE_SPEC;
        }

        if ((c >= '0') && (c <= '9')) {
            return VALIDE_SPEC;
        }
        if ((c >= 'A') && (c <= 'Z')) {
            return VALIDE_SPEC;
        }
        if ((c >= '^') && (c <= '~')) {
            return VALIDE_SPEC;
        }
        switch (c) {
            case '!':
            case '#':
            case '$':
            case '%':
            case '&':
            case '\'':
            case '*':
            case '+':
            case '-':
            case '/':
            case '=':
            case '?':
                return VALIDE_SPEC;
            default:
                return HORS_SPEC;
        }
    }


    private static class InternalEmailCore implements EmailCore {

        String addrSpec;
        String realName = "";

        private InternalEmailCore(String addrSpec) {
            this.addrSpec = addrSpec;
        }

        private InternalEmailCore(EmailCore emailCore) {
            this.addrSpec = emailCore.getAddrSpec();
            this.realName = emailCore.getRealName();
        }

        @Override
        public String getRealName() {
            return realName;
        }

        @Override
        public String getAddrSpec() {
            return addrSpec;
        }

        private void setRealName(String realName) {
            this.realName = realName;
        }

    }

}
