
package com.fsck.k9.mail.internet;

import com.fsck.k9.helper.Utility;
import com.fsck.k9.mail.MessagingException;
import org.apache.james.mime4j.codec.EncoderUtil;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.*;

public class MimeHeader
{
    private static final String[] EMPTY_STRING_ARRAY = new String[0];

    /**
     * Application specific header that contains Store specific information about an attachment.
     * In IMAP this contains the IMAP BODYSTRUCTURE part id so that the ImapStore can later
     * retrieve the attachment at will from the server.
     * The info is recorded from this header on LocalStore.appendMessages and is put back
     * into the MIME data by LocalStore.fetch.
     */
    public static final String HEADER_ANDROID_ATTACHMENT_STORE_DATA = "X-Android-Attachment-StoreData";

    public static final String HEADER_CONTENT_TYPE = "Content-Type";
    public static final String HEADER_CONTENT_TRANSFER_ENCODING = "Content-Transfer-Encoding";
    public static final String HEADER_CONTENT_DISPOSITION = "Content-Disposition";
    public static final String HEADER_CONTENT_ID = "Content-ID";

    /**
     * Fields that should be omitted when writing the header using writeTo()
     */
    private static final String[] writeOmitFields =
    {
//        HEADER_ANDROID_ATTACHMENT_DOWNLOADED,
//        HEADER_ANDROID_ATTACHMENT_ID,
        HEADER_ANDROID_ATTACHMENT_STORE_DATA
    };

    protected ArrayList<Field> mFields = new ArrayList<Field>();

    public void clear()
    {
        mFields.clear();
    }

    public String getFirstHeader(String name)
    {
        String[] header = getHeader(name);
        if (header == null)
        {
            return null;
        }
        return header[0];
    }

    public void addHeader(String name, String value)
    {
        mFields.add(new Field(name, MimeUtility.foldAndEncode(value)));
    }

    public void setHeader(String name, String value)
    {
        if (name == null || value == null)
        {
            return;
        }
        removeHeader(name);
        addHeader(name, value);
    }

    public Set<String> getHeaderNames()
    {
        Set<String> names = new HashSet<String>();
        for (Field field : mFields)
        {
            names.add(field.name);
        }
        return names;
    }

    public String[] getHeader(String name)
    {
        ArrayList<String> values = new ArrayList<String>();
        for (Field field : mFields)
        {
            if (field.name.equalsIgnoreCase(name))
            {
                values.add(field.value);
            }
        }
        if (values.size() == 0)
        {
            return null;
        }
        return values.toArray(EMPTY_STRING_ARRAY);
    }

    public void removeHeader(String name)
    {
        ArrayList<Field> removeFields = new ArrayList<Field>();
        for (Field field : mFields)
        {
            if (field.name.equalsIgnoreCase(name))
            {
                removeFields.add(field);
            }
        }
        mFields.removeAll(removeFields);
    }

    public void writeTo(OutputStream out) throws IOException, MessagingException
    {
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out), 1024);
        for (Field field : mFields)
        {
            if (!Utility.arrayContains(writeOmitFields, field.name))
            {
                String v = field.value;

                if (hasToBeEncoded(v))
                {
                    v = EncoderUtil.encodeEncodedWord(
                            field.value,
                            EncoderUtil.Usage.WORD_ENTITY
                        );
                }

                writer.write(field.name + ": " + v + "\r\n");
            }
        }
        writer.flush();
    }

    // encode non printable characters except LF/CR codes.
    public boolean hasToBeEncoded(String text)
    {
        for (int i = 0; i < text.length(); i++)
        {
            char c = text.charAt(i);
            if (c < 0x20 || 0x7e < c)   // non printable
            {
                if (c != 0x0a && c != 0x0d)   // non LF/CR
                {
                    return true;
                }
            }
        }

        return false;
    }

    class Field
    {
        String name;

        String value;

        public Field(String name, String value)
        {
            this.name = name;
            this.value = value;
        }

        @Override
        public String toString()
        {
            StringBuilder sb = new StringBuilder("(");
            sb.append(name).append('=').append(value).append(')');
            return sb.toString();
        }
    }
}

@@ -2490,208 +2490,26 @@
 s = 
-new ArrayList%3CString%3E();%0A        for (Field field : mFields)%0A        %7B%0A            if (field.name.equalsIgnoreCase(name))%0A            %7B%0A                values.add(field.value);%0A            %7D%0A        %7D
+findHeaders(name);
 %0A   
@@ -2680,32 +2680,33 @@
 ing name)%0A    %7B%0A
+%0A
         ArrayLis
@@ -2711,26 +2711,171 @@
 ist%3C
-Field%3E removeField
+String%3E removeFields = findHeaders(name);%0A        mFields.removeAll(removeFields);%0A    %7D%0A%0A    private ArrayList findHeaders(String name) %7B%0A%09ArrayList%3CString%3E value
 s = 
@@ -2884,29 +2884,30 @@
 w ArrayList%3C
-Field
+String
 %3E();%0A       
@@ -2911,58 +2911,123 @@
     
-for (Field field : mFields)%0A        %7B%0A            
+Iterator%3CField%3E iter = mFields.iterator();%0A        while (iter.hasNext())%0A        %7B%0A%09%09Field field = iter.next();%0A%09%09
 if (
@@ -3063,77 +3063,45 @@
 ame)
+ 
 )%0A
-            %7B%0A                removeFields.add(field);%0A            
+%09%09%7B%0A%09%09%09values.add(field.value);%0A%09%09
 %7D%0A  
@@ -3108,24 +3108,25 @@
       %7D%0A
+%0A
         
 mFields.
@@ -3121,39 +3121,21 @@
     
-mFields.removeAll(removeFields)
+return values
 ;%0A  
@@ -3131,32 +3131,33 @@
  values;%0A    %7D%0A%0A
+%0A
     public void 

refactor getHeaders and removeHeaders to use a common method and an iterator to address a Market FC: