/*
 * 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.imap;

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

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.channels.Channels;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;

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

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

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

    /**
     * Tag for current command
     */
    protected String tag;

    /**
     * IMAP capabilities supported
     */
    protected String capabilities = "IMAP4REV1 IDLE ID";

    /**
     * Number of messages
     */
    protected int numberOfMessages = 0;

    /**
     * Number of recent messages
     */
    protected int numberOfRecentMessages = 0;

    /**
     * Send greetings.
     *
     * @throws IOException unable to write to socket
     */
    @Override
    public void sendGreetings(OutputStream outputStream) throws IOException {
        untagged(outputStream, "OK [CAPABILITY " + capabilities + "] IMAPHandler");
    }

    /**
     * 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();
    }

    /**
     * Send a tagged response.
     *
     * @param resp the response to send
     * @throws IOException unable to read/write to socket
     */
    public void tagged(OutputStream outputStream, final String resp) throws IOException {
        println(outputStream, tag + " " + resp);
    }

    /**
     * Send an untagged response.
     *
     * @param resp the response to send
     * @throws IOException unable to read/write to socket
     */
    public void untagged(OutputStream outputStream, final String resp) throws IOException {
        println(outputStream, "* " + resp);
    }

    /**
     * Send a tagged OK response.
     *
     * @throws IOException unable to read/write to socket
     */
    public void ok(OutputStream outputStream) throws IOException {
        tagged(outputStream, "OK");
    }

    /**
     * Send a tagged OK response with a message.
     *
     * @param msg the message to send
     * @throws IOException unable to read/write to socket
     */
    public void ok(OutputStream outputStream, final String msg) throws IOException {
        tagged(outputStream, "OK " + (msg != null ? msg : ""));
    }

    /**
     * Send a tagged NO response with a message.
     *
     * @param msg the message to send
     * @throws IOException unable to read/write to socket
     */
    public void no(OutputStream outputStream, final String msg) throws IOException {
        tagged(outputStream, "NO " + (msg != null ? msg : ""));
    }

    /**
     * Send a tagged BAD response with a message.
     *
     * @param msg the message to send
     * @throws IOException unable to read/write to socket
     */
    public void bad(OutputStream outputStream, final String msg) throws IOException {
        tagged(outputStream, "BAD " + (msg != null ? msg : ""));
    }

    /**
     * Send an untagged BYE response with a message, then exit.
     *
     * @param msg the message to send
     * @throws IOException unable to read/write to socket
     */
    public void bye(OutputStream outputStream, final String msg) throws IOException {
        untagged(outputStream, "BYE " + (msg != null ? msg : ""));
        exit();
    }

    /**
     * Send a "continue" command.
     *
     * @throws IOException unable to read/write to socket
     */
    public void cont(OutputStream outputStream) throws IOException {
        println(outputStream, "+ please continue");
    }

    /**
     * Send a "continue" command with a message.
     *
     * @throws IOException unable to read/write to socket
     */
    public void cont(OutputStream outputStream, String msg) throws IOException {
        println(outputStream, "+ " + (msg != null ? msg : ""));
    }

    /**
     * Handle command.
     *
     * @throws IOException unable to read/write to socket
     */
    @Override
    public void handleCommand(InputStream inputStream, OutputStream outputStream) throws IOException {
        currentLine = super.readLine(inputStream);
        if (currentLine == null) {
            // probably just EOF because the socket was closed
            //LOGGER.severe("Current line is null!");
            exit();
            return;
        }
        StringTokenizer ct = new StringTokenizer(currentLine, " ");
        if (!ct.hasMoreTokens()) {
            logger.log(Level.SEVERE, "ERROR no command tag: {0}", escape(currentLine));
            bad(outputStream, "no command tag");
            return;
        }
        tag = ct.nextToken();
        if (!ct.hasMoreTokens()) {
            logger.log(Level.SEVERE, "ERROR no command: {0}",
                    escape(currentLine));
            bad(outputStream, "no command");
            return;
        }
        final String commandName = ct.nextToken().toUpperCase();
        if (commandName.isEmpty()) {
            logger.severe("Command name is empty!");
            exit();
            return;
        }
        if (commandName.equals("LOGIN")) {
            login(outputStream);
        } else if (commandName.equals("AUTHENTICATE")) {
            String mech = ct.nextToken().toUpperCase();
            String ir = null;
            if (ct.hasMoreTokens()) {
                ir = ct.nextToken();
            }
            authenticate(inputStream, outputStream, mech, ir);
        } else if (commandName.equals("CAPABILITY")) {
            capability(outputStream);
        } else if (commandName.equals("NOOP")) {
            noop(outputStream);
        } else if (commandName.equals("SELECT")) {
            select(outputStream, currentLine);
        } else if (commandName.equals("EXAMINE")) {
            examine(outputStream, currentLine);
        } else if (commandName.equals("LIST")) {
            list(outputStream, currentLine);
        } else if (commandName.equals("IDLE")) {
            idle(inputStream, outputStream);
        } else if (commandName.equals("FETCH")) {
            fetch(outputStream, currentLine);
        } else if (commandName.equals("STORE")) {
            store(outputStream, currentLine);
        } else if (commandName.equals("SEARCH")) {
            search(outputStream, currentLine);
        } else if (commandName.equals("APPEND")) {
            append(inputStream, outputStream, currentLine);
        } else if (commandName.equals("CLOSE")) {
            close(outputStream);
        } else if (commandName.equals("LOGOUT")) {
            logout(outputStream);
        } else if (commandName.equals("UID")) {
            String subcommandName = ct.nextToken().toUpperCase();
            if (subcommandName.equals("FETCH")) {
                uidfetch(outputStream, currentLine);
            } else if (subcommandName.equals("STORE")) {
                uidstore(outputStream, currentLine);
            } else {
                logger.log(Level.SEVERE, "ERROR UID command unknown: {0}", subcommandName);
                bad(outputStream, "unknown UID command");
            }
        } else if (commandName.equals("ID")) {
            id(outputStream, currentLine);
        } else if (commandName.equals("ENABLE")) {
            enable(outputStream, currentLine);
        } else if (commandName.equals("CREATE")) {
            create(outputStream, currentLine);
        } else if (commandName.equals("DELETE")) {
            delete(outputStream, currentLine);
        } else if (commandName.equals("STATUS")) {
            status(outputStream, currentLine);
        } else if (commandName.equals("NAMESPACE")) {
            namespace(outputStream);
        } else {
            logger.log(Level.SEVERE, "ERROR command unknown: {0}",
                    escape(currentLine));
            bad(outputStream, "unknown command");
        }
    }

    /**
     * LOGIN command.
     *
     * @throws IOException unable to read/write to socket
     */
    public void login(OutputStream outputStream) throws IOException {
        ok(outputStream, "[CAPABILITY " + capabilities + "]");
    }

    /**
     * AUTHENTICATE command.
     *
     * @throws IOException unable to read/write to socket
     */
    public void authenticate(InputStream inputStream, OutputStream outputStream, String mech, String ir) throws IOException {
        if (mech.equals("LOGIN"))
            authlogin(inputStream, outputStream, ir);
        else if (mech.equals("PLAIN"))
            authplain(inputStream, outputStream, ir);
        else
            bad(outputStream, "AUTHENTICATE not supported");
    }

    /**
     * AUTHENTICATE LOGIN command.
     *
     * @throws IOException unable to read/write to socket
     */
    public void authlogin(InputStream inputStream, OutputStream outputStream, String ir) throws IOException {
        if (ir != null)
            bad(outputStream, "AUTHENTICATE LOGIN does not support initial response");
        cont(outputStream, base64encode("Username"));
        String username = readLine(inputStream);
        cont(outputStream, base64encode("Password"));
        String password = readLine(inputStream);
        ok(outputStream, "[CAPABILITY " + capabilities + "]");
    }

    /**
     * AUTHENTICATE PLAIN command.
     *
     * @throws IOException unable to read/write to socket
     */
    public void authplain(InputStream inputStream, OutputStream outputStream, String ir) throws IOException {
        if (ir == null) {
            cont(outputStream, "");
            String resp = readLine(inputStream);
        }
        ok(outputStream, "[CAPABILITY " + capabilities + "]");
    }

    /**
     * CAPABILITY command.
     *
     * @throws IOException unable to read/write to socket
     */
    public void capability(OutputStream outputStream) throws IOException {
        untagged(outputStream, "CAPABILITY " + capabilities);
        ok(outputStream);
    }

    /**
     * SELECT command.
     *
     * @throws IOException unable to read/write to socket
     */
    public void select(OutputStream outputStream, String line) throws IOException {
        untagged(outputStream, numberOfMessages + " EXISTS");
        untagged(outputStream, numberOfRecentMessages + " RECENT");
        ok(outputStream);
    }

    /**
     * EXAMINE command.
     *
     * @throws IOException unable to read/write to socket
     */
    public void examine(OutputStream outputStream, String line) throws IOException {
        untagged(outputStream, numberOfMessages + " EXISTS");
        untagged(outputStream, numberOfRecentMessages + " RECENT");
        ok(outputStream);
    }

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

    /**
     * IDLE command.
     *
     * @throws IOException unable to read/write to socket
     */
    public void idle(InputStream inputStream, OutputStream outputStream) throws IOException {
        cont(outputStream);
        idleWait(inputStream, outputStream);
        ok(outputStream);
    }

    @Override
    protected String readLine(InputStream inputStream) throws IOException {
        currentLine = super.readLine(inputStream);
        if (currentLine == null) {
            logger.severe("Current line is null!");
            exit();
        }
        return currentLine;
    }

    protected void idleWait(InputStream inputStream, OutputStream outputStream) throws IOException {
        String line = readLine(inputStream);
        if (line != null && !line.equalsIgnoreCase("DONE")) {
            logger.severe("Didn't get DONE response to IDLE");
            exit();
        }
    }

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

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

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

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

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

    /**
     * APPEND command.
     *
     * @throws IOException unable to read/write to socket
     */
    public void append(InputStream inputStream, OutputStream outputStream, String line) throws IOException {
        int left = line.lastIndexOf('{');
        int right = line.indexOf('}', left);
        int bytes = Integer.parseInt(line.substring(left + 1, right));
        cont(outputStream, "waiting for message");
        collectMessage(inputStream, outputStream, bytes);
        ok(outputStream);
    }

    /**
     * ID command.
     *
     * @throws IOException unable to read/write to socket
     */
    public void id(OutputStream outputStream, String line) throws IOException {
        untagged(outputStream, "ID NIL");
        ok(outputStream);
    }

    /**
     * ENABLE command.
     *
     * @throws IOException unable to read/write to socket
     */
    public void enable(OutputStream outputStream, String line) throws IOException {
        no(outputStream, "can't enable");
    }

    /**
     * CREATE command.
     *
     * @throws IOException unable to read/write to socket
     */
    public void create(OutputStream outputStream, String line) throws IOException {
        no(outputStream, "can't create");
    }

    /**
     * DELETE command.
     *
     * @throws IOException unable to read/write to socket
     */
    public void delete(OutputStream outputStream, String line) throws IOException {
        no(outputStream, "can't delete");
    }

    /**
     * STATUS command.
     *
     * @throws IOException unable to read/write to socket
     */
    public void status(OutputStream outputStream, String line) throws IOException {
        no(outputStream, "can't get status");
    }

    /**
     * NAMESPACE command.
     *
     * @throws IOException unable to read/write to socket
     */
    public void namespace(OutputStream outputStream) throws IOException {
        no(outputStream, "no namespaces");
    }

    /**
     * Collect "bytes" worth of data for the message being appended.
     */
    protected void collectMessage(InputStream inputStream, OutputStream outputStream, int bytes) throws IOException {
        readLiteral(inputStream, outputStream, bytes);    // read the data and throw it away
        super.readLine(inputStream);    // data followed by a newline
    }

    /**
     * Read a literal of "bytes" bytes and return it as a UTF-8 string.
     */
    protected String readLiteral(InputStream inputStream, OutputStream outputStream, int bytes) throws IOException {
        println(outputStream, "+");
        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;
        }
        return new String(data, StandardCharsets.UTF_8);
    }

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

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

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

    /**
     * Base64 encode the string.
     */
    protected String base64encode(String s) throws IOException {
        return new String(Base64.getEncoder().encode(s.getBytes(StandardCharsets.US_ASCII)),
                StandardCharsets.US_ASCII);
    }

    /**
     * Escape any non-printable characters in "s",
     * limiting total length to about 100 characters.
     */
    private String escape(String s) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            if (sb.length() >= 100) {
                sb.append("...");
                break;
            }
            char c = s.charAt(i);
            if (c < ' ' || c == '\177') {
                if (c == '\r')
                    sb.append("\\r");
                else if (c == '\n')
                    sb.append("\\n");
                else if (c == '\t')
                    sb.append("\\t");
                else
                    sb.append('\\').append(String.format("%03o", (int) c));
            } else if (c >= '\200') {
                sb.append("\\u").append(String.format("%04x", (int) c));
            } else
                sb.append(c);
        }
        return sb.toString();
    }
}
