package ru.yandex.wmtools.common.service;

import java.util.ArrayList;
import java.util.List;

import org.jdom.Document;
import org.jdom.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ru.yandex.common.util.collections.Pair;
import ru.yandex.wmtools.common.data.info.EmailInfo;
import ru.yandex.wmtools.common.error.InternalException;

/**
 * Email validation support. Used to check whether email is valid (was verified).
 *
 * @author Andrey Mima (amima@yandex-team.ru)
 * @author avhaliullin
 */
public class ValidatorService extends AbstractBlackboxService {
    private static final Logger log = LoggerFactory.getLogger(ValidatorService.class);

    public Boolean isEmailValid(Long userId, String email) throws InternalException {
        Document doc = getDocument(Pair.of(IdentificationMethod.UID, String.valueOf(userId)),
                Method.USER_INFO,
                createParams()
                        .addParam("emails", "testone")
                        .addParam("addrtotest", email));

        if (doc != null) {
            List elements = doc.getRootElement().getChild("address-list").getChildren("address");
            for (Object tagObj : elements) {
                if (tagObj instanceof Element) {
                    Element tag = (Element) tagObj;
                    return "1".equals(tag.getAttributeValue("validated"));
                }
            }
        }

        return false;
    }

    public List<EmailInfo> getEmails(Long userId) throws InternalException {
        List<EmailInfo> emails = new ArrayList<EmailInfo>();

        Document doc = getDocument(Pair.of(IdentificationMethod.UID, String.valueOf(userId)),
                Method.USER_INFO,
                createParams()
                        .addParam("emails", "getall"));

        if (doc != null) {
            List elements = doc.getRootElement().getChild("address-list").getChildren("address");
            for (Object tagObj : elements) {
                if (tagObj instanceof Element) {
                    Element tag = (Element) tagObj;
                    emails.add(new EmailInfo(tag.getText(), "1".equals(tag.getAttributeValue("validated"))));
                }
            }
        }
        return emails;
    }

    public String getDefaultEmail(Long userId, String username) {
        List<EmailInfo> emails = null;
        try {
            emails = getEmails(userId);
        } catch (InternalException e) {
            log.warn("Failed to get user emails", e);
            return null;
        }
        log.debug("username: " + username + " emails.size: " + emails.size());
        for (EmailInfo email : emails) {
            log.debug("email.getAddress: " + email.getAddress());
            if (email.getAddress() == null) {
                log.error("Email address is null, but emails size not 0, userId = " + Long.toString(userId) +
                        ", username = " + username);
            }
            if (email.getAddress() != null && email.getAddress().equals(username.concat("@yandex.ru")) && email.isValid()) {
                return email.getAddress();
            }
        }

        return null;
    }
}
