#include "handler.ih"

void Handler::mailHeaders()
{
    static Pattern bdry( 
                R"(multipart/mixed;\s+boundary=("?)([^\"]+))" 
            );

    MailHeaders mh(cin);

    for (string const &hdr: mh)
    {
        if (hdr.find("From: ") == 0)                // set the From: address
        {
            d_from = hdr.substr(hdr.find('<') + 1);
            d_from.resize(d_from.rfind('>'));
        }

//  keep our local time: the Date specification of the incoming mail is
// irrelevant:
//        else if (hdr.find("Date: ") == 0)           // set the Date:
//            d_date = hdr;

        else if (bdry << hdr)                       // set the boundary
            d_boundary = "--" + bdry[2];

        else if (hdr.find("Subject: ") == 0)        // inspect the Subject
        {
            string subject = String::lc(hdr);
                                                    // check for 'public key'
            d_publicKey = subject.find("public key") != string::npos;

            if (not d_publicKey)                    // no public key
            {
                                                    // check for 'pdf'
                d_pdf2from = subject.find("pdf") != string::npos;
                if (d_pdf2from)
                    g_options.onlyPdf();            // if so: only write the
                                                    // pdf
            }
        }
    }

    if (d_from.empty())
        throw Exception{NO_MAIL} << "Mail: no From: address";

    g_mailer.setTo(d_from);

    if (d_date.empty())
        throw Exception{REPLY} << "Mail: without Date: header";

    if (not d_publicKey and d_boundary.empty())
        throw Exception{REPLY} << "Mail: without multipart/mixed; boundary "
                                                                "definition";
}




