package com.commit451.gitlab.views;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.content.Context;
import android.support.v7.widget.AppCompatAutoCompleteTextView;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Patterns;
import android.widget.ArrayAdapter;

import com.commit451.gitlab.R;

import java.util.ArrayList;

/**
 * Automagically fills in email accounts
 * Created by John on 8/13/15.
 */
public class EmailAutoCompleteTextView extends AppCompatAutoCompleteTextView {

    public EmailAutoCompleteTextView(Context context) {
        super(context);
        init();
    }

    public EmailAutoCompleteTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public EmailAutoCompleteTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        if (isInEditMode()) { return; }
        ArrayList<String> accounts = getEmailAccounts();
        if (accounts != null && !accounts.isEmpty()) {
            ArrayAdapter<String> adapter = new ArrayAdapter<>(getContext(), R.layout.support_simple_spinner_dropdown_item, accounts);
            setAdapter(adapter);
        }
    }

    /**
     * Get all the accounts that appear to be email accounts
     * @return list of email accounts
     */
    private ArrayList<String> getEmailAccounts() {
        ArrayList<String> emailAccounts = new ArrayList<>();
        AccountManager manager = (AccountManager) getContext().getSystemService(Context.ACCOUNT_SERVICE);
        final Account[] accounts = manager.getAccounts();
        for (Account account : accounts) {
            if (!TextUtils.isEmpty(account.name) && Patterns.EMAIL_ADDRESS.matcher(account.name).matches()) {
                emailAccounts.add(account.name);
            }
        }
        return emailAccounts;
    }
}
@@ -390,16 +390,93 @@
 rayList;
+%0Aimport java.util.Collection;%0Aimport java.util.HashSet;%0Aimport java.util.Set;
 %0A%0A/**%0A *
@@ -1094,33 +1094,34 @@
 ; %7D%0A        
-ArrayList
+Collection
 %3CString%3E acc
@@ -1278,16 +1278,36 @@
 ntext(),
+%0A                   
  R.layou
@@ -1345,17 +1345,53 @@
 wn_item,
- 
+%0A                    new ArrayList%3C%3E(
 accounts
@@ -1391,16 +1391,17 @@
 ccounts)
+)
 ;%0A      
@@ -1508,24 +1508,66 @@
 ail accounts
+. HashSet so that we do not get duplicates
 %0A     * @ret
@@ -1613,24 +1613,18 @@
 private 
-ArrayLis
+Se
 t%3CString
@@ -1654,24 +1654,22 @@
         
-ArrayLis
+HashSe
 t%3CString
@@ -1686,32 +1686,30 @@
 ounts = new 
-ArrayLis
+HashSe
 t%3C%3E();%0A     

Use hashset for getting autocomplete accounts so that we do not get duplicates.