package ru.yandex.wmconsole.servantlet.verification;

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

import org.apache.commons.lang.StringUtils;

import ru.yandex.common.framework.core.ServRequest;
import ru.yandex.common.framework.core.ServResponse;
import ru.yandex.common.framework.pager.Pager;
import ru.yandex.wmconsole.data.VerificationStateEnum;
import ru.yandex.wmconsole.data.info.BriefHostInfo;
import ru.yandex.wmconsole.data.info.ShortHostInfo;
import ru.yandex.wmconsole.data.wrappers.ShortHostInfoWrapper;
import ru.yandex.wmconsole.servantlet.BriefHostInfoHelper;
import ru.yandex.wmconsole.servantlet.WMCAuthenticationServantlet;
import ru.yandex.wmconsole.verification.VerificationTypeEnum;
import ru.yandex.wmtools.common.error.InternalException;
import ru.yandex.wmtools.common.error.UserException;
import ru.yandex.wmtools.common.util.XmlConvertableCollectionWrapper;

public class NotVerifiedHostListServantlet extends WMCAuthenticationServantlet {
    @Override
    public void doProcess(ServRequest req, ServResponse res, long userId) throws InternalException, UserException {
        Pager pager = createOutputStrategy(req).createPager();

        if (!StringUtils.isEmpty(req.getParam(BriefHostInfoHelper.PARAM_HOST))) {
            BriefHostInfo hostInfo = getHostInfo(req);
            if (hostInfo != null) {
                List<ShortHostInfo> shortHostInfo = getHostInfoService().getShortHostInfo(userId, hostInfo);
                if (shortHostInfo != null) {
                    List<ShortHostInfo> result = new ArrayList<>(shortHostInfo.size());
                    if (shortHostInfo.isEmpty()) {
                        result.add(new ShortHostInfo(hostInfo.getId(), hostInfo.getName(),
                                VerificationStateEnum.NEVER_VERIFIED,
                                VerificationTypeEnum.DEFAULT));
                    } else {
                        for (ShortHostInfo info : shortHostInfo) {
                            if (!info.getVerificationState().isVerified()) {
                                result.add(info);
                            }
                        }
                    }
                    res.addData(
                            XmlConvertableCollectionWrapper.wrap(result, ShortHostInfoWrapper.class,
                                    "not-verified-host-list")
                    );
                    res.addData(pager);
                }

            }
        } else {
            List<ShortHostInfo> hostList = getHostInfoService().getNotVerifiedShortHostList(userId, pager);

            res.addData(
                    XmlConvertableCollectionWrapper.wrap(hostList, ShortHostInfoWrapper.class,
                            "not-verified-host-list")
            );
            res.addData(pager);

        }
    }
}
