package foundation.e.mail.activity.setup;

import android.content.Context;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import foundation.e.mail.Account;
import foundation.e.mail.K9;
import foundation.e.mail.Preferences;
import foundation.e.mail.controller.MessagingController;

public class GoogleAccountCreator {
    public static void createAccount(Context context, String emailId) {
        Preferences preferences = Preferences.getPreferences(context);

        AccountConfigImpl accountConfig = new AccountConfigImpl(preferences);
        accountConfig.setName(emailId);
        accountConfig.setEmail(emailId);
        accountConfig.setDescription(emailId);
        accountConfig.setTrashFolderName("[Gmail]/Trash");
        accountConfig.setArchiveFolderName("[Gmail]/All Mail");
        accountConfig.setDraftsFolderName("[Gmail]/Drafts");
        accountConfig.setInboxFolderName("INBOX");
        accountConfig.setSentFolderName("[Gmail]/Sent Mail");
        accountConfig.setSpamFolderName("[Gmail]/Spam");
        accountConfig.setAutoExpandFolderName("INBOX");

        try {
            accountConfig.setStoreUri("imap+ssl+://XOAUTH2:" +
                    URLEncoder.encode(emailId, "UTF-8") + ":@imap.gmail.com");
            accountConfig.setTransportUri("smtp+ssl+://" +
                    URLEncoder.encode(emailId, "UTF-8") +
                    "::XOAUTH2@smtp.gmail.com");
        }
        catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        Account account = preferences.newAccount();
        account.setDeviceAccount(true);
        account.loadConfig(accountConfig);

        MessagingController.getInstance(context).listFoldersSynchronous(account, true, null);
        MessagingController.getInstance(context)
                .synchronizeMailbox(account, account.getInboxFolderName(), null, null);

        account.save(preferences);

        preferences.setDefaultAccount(account);

        K9.setServicesEnabled(context);
    }
}

