/*
 * Copyright (c) 2009, 2023 Oracle and/or its affiliates. All rights reserved.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v. 2.0, which is available at
 * http://www.eclipse.org/legal/epl-2.0.
 *
 * This Source Code may also be made available under the following Secondary
 * Licenses when the conditions for such availability set forth in the
 * Eclipse Public License v. 2.0 are satisfied: GNU General Public License,
 * version 2 with the GNU Classpath Exception, which is available at
 * https://www.gnu.org/software/classpath/license.html.
 *
 * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
 */

package org.xbib.net.mail.test.smtp;

import org.xbib.net.mail.test.test.ProtocolHandler;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.nio.channels.Channels;
import java.nio.charset.StandardCharsets;
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Handle connection.
 *
 * @author Bill Shannon
 */
public class SMTPHandler extends ProtocolHandler {

    private static final Logger logger = Logger.getLogger(SMTPHandler.class.getName());

    /**
     * Current line.
     */
    private String currentLine;

    /**
     * A message being accumulated.
     */
    private ByteArrayOutputStream messageStream;

    /**
     * SMTP extensions supported.
     */
    protected Set<String> extensions = new HashSet<String>();

    /**
     * Send greetings.
     *
     * @throws IOException unable to write to socket
     */
    @Override
    public void sendGreetings(OutputStream outputStream) throws IOException {
        println(outputStream, "220 localhost dummy server ready");
    }

    /**
     * Send String to socket.
     *
     * @param str String to send
     * @throws IOException unable to write to socket
     */
    public void println(OutputStream outputStream, final String str) throws IOException {
        Channels.newChannel(outputStream).write(StandardCharsets.UTF_8.encode(str + "\r\n"));
        outputStream.flush();
    }

    /**
     * Handle command.
     *
     * @throws IOException unable to read/write to socket
     */
    @Override
    public void handleCommand(InputStream inputStream, OutputStream outputStream) throws IOException {
        currentLine = readLine(inputStream);
        if (currentLine == null) {
            return;
        }
        final StringTokenizer st = new StringTokenizer(currentLine, " ");
        final String commandName = st.nextToken().toUpperCase();
        switch (commandName) {
            case "HELO" -> helo(outputStream);
            case "EHLO" -> ehlo(outputStream);
            case "MAIL" -> mail(outputStream, currentLine);
            case "RCPT" -> rcpt(outputStream, currentLine);
            case "DATA" -> data(inputStream, outputStream);
            case "BDAT" -> bdat(inputStream,outputStream, currentLine);
            case "NOOP" -> noop(outputStream);
            case "RSET" -> rset(outputStream);
            case "QUIT" -> quit(outputStream);
            case "AUTH" -> auth(inputStream, outputStream, currentLine);
            default -> {
                logger.log(Level.SEVERE, "ERROR command unknown: {0}", commandName);
                println(outputStream, "-ERR unknown command");
            }
        }
    }

    @Override
    protected String readLine(InputStream inputStream) throws IOException {
        currentLine = super.readLine(inputStream);
        if (currentLine == null) {
            exit();
        }
        return currentLine;
    }

    /**
     * HELO command.
     *
     * @throws IOException unable to read/write to socket
     */
    public void helo(OutputStream outputStream) throws IOException {
        println(outputStream, "220 Ok");
    }

    /**
     * EHLO command.
     *
     * @throws IOException unable to read/write to socket
     */
    public void ehlo(OutputStream outputStream) throws IOException {
        println(outputStream, "250-hello");
        for (String ext : extensions)
            println(outputStream, "250-" + ext);
        println(outputStream, "250 AUTH PLAIN");    // PLAIN is simplest to fake
    }

    /**
     * MAIL command.
     *
     * @throws IOException unable to read/write to socket
     */
    public void mail(OutputStream outputStream, String line) throws IOException {
        ok(outputStream);
    }

    /**
     * RCPT command.
     *
     * @throws IOException unable to read/write to socket
     */
    public void rcpt(OutputStream outputStream, String line) throws IOException {
        ok(outputStream);
    }

    /**
     * DATA command.
     *
     * @throws IOException unable to read/write to socket
     */
    public void data(InputStream inputStream, OutputStream outputStream) throws IOException {
        println(outputStream, "354 go ahead");
        readMessage(inputStream);
        ok(outputStream);
    }

    /**
     * BDAT command.
     *
     * @throws IOException unable to read/write to socket
     */
    public void bdat(InputStream inputStream, OutputStream outputStream, String line) throws IOException {
        StringTokenizer st = new StringTokenizer(line, " ");
        String commandName = st.nextToken();
        int bytes = Integer.parseInt(st.nextToken());
        boolean last = st.hasMoreTokens() &&
                st.nextToken().equalsIgnoreCase("LAST");
        readBdatMessage(inputStream, bytes, last);
        ok(outputStream);
    }

    /**
     * Allow subclasses to override to save the message.
     */
    protected void setMessage(byte[] msg) {
    }

    /**
     * Consume the message and save it.
     */
    protected void readMessage(InputStream inputStream) throws IOException {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        PrintWriter pw = new PrintWriter(new OutputStreamWriter(bos, StandardCharsets.UTF_8));
        String line;
        while ((line = super.readLine(inputStream)) != null) {
            if (line.equals("."))
                break;
            if (line.startsWith("."))
                line = line.substring(1);
            pw.print(line);
            pw.print("\r\n");
        }
        pw.close();
        setMessage(bos.toByteArray());
    }

    /**
     * Consume a chunk of the message and save it.
     * Save the entire message when the last chunk is received.
     */
    protected void readBdatMessage(InputStream inputStream, int bytes, boolean last) throws IOException {
        byte[] data = new byte[bytes];
        int len = data.length;
        int off = 0;
        int n;
        while (len > 0 && (n = inputStream.read(data, off, len)) > 0) {
            off += n;
            len -= n;
        }
        if (messageStream == null)
            messageStream = new ByteArrayOutputStream();
        messageStream.write(data);
        if (last) {
            setMessage(messageStream.toByteArray());
            messageStream = null;
        }
    }

    /**
     * NOOP command.
     *
     * @throws IOException unable to read/write to socket
     */
    public void noop(OutputStream outputStream) throws IOException {
        ok(outputStream);
    }

    /**
     * RSET command.
     *
     * @throws IOException unable to read/write to socket
     */
    public void rset(OutputStream outputStream) throws IOException {
        ok(outputStream);
    }

    /**
     * QUIT command.
     *
     * @throws IOException unable to read/write to socket
     */
    public void quit(OutputStream outputStream) throws IOException {
        println(outputStream, "221 BYE");
        exit();
    }

    /**
     * AUTH command.
     *
     * @throws IOException unable to read/write to socket
     */
    public void auth(InputStream inputStream, OutputStream outputStream, String line) throws IOException {
        println(outputStream, "235 Authorized");
    }

    protected void ok(OutputStream outputStream) throws IOException {
        println(outputStream, "250 OK");
    }
}
