package ru.yandex.wmconsole.servantlet.services;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Required;

import ru.yandex.common.framework.core.ServRequest;
import ru.yandex.common.framework.core.ServResponse;
import ru.yandex.wmconsole.data.ServiceEnum;
import ru.yandex.wmconsole.data.info.BriefHostInfo;
import ru.yandex.wmconsole.data.info.ShortServiceOptionsInfo;
import ru.yandex.wmconsole.data.wrappers.NoDataWrapper;
import ru.yandex.wmconsole.servantlet.WMCAuthorizedHostOperationServantlet;
import ru.yandex.wmconsole.service.ServiceOptionsService;
import ru.yandex.wmtools.common.error.InternalException;
import ru.yandex.wmtools.common.error.UserException;

/**
 * Changes options of specified services.
 *
 * @author ailyin
 */
public class ServicesOptionsChangeServantlet extends WMCAuthorizedHostOperationServantlet {
    private static final String OPTION_PREFIX = "option";

    private ServiceOptionsService serviceOptionsService;

    @Override
    protected void doProcess(ServRequest req, ServResponse res, long userId) throws UserException, InternalException {

        BriefHostInfo hostInfo = getHostInfoAndVerify(req, userId);
        List<ShortServiceOptionsInfo> options = new ArrayList<ShortServiceOptionsInfo>();
        boolean outputOkTag = false;
        for (Map.Entry<String, String> param : (Set<Map.Entry<String, String>>) req.getParams().entrySet()) {
            if (param.getKey().startsWith(OPTION_PREFIX)) {
                ServiceEnum service;
                try {
                    service = ServiceEnum.R.fromValueOrNull(
                            Integer.parseInt(param.getKey().substring(OPTION_PREFIX.length())));
                } catch (NumberFormatException e) {
                    continue;
                }
                boolean enabled = Boolean.parseBoolean(param.getValue());

                if (service != null) {
                    outputOkTag = true;
                    options.add(new ShortServiceOptionsInfo(service, enabled));
                }
            }
        }

        serviceOptionsService.updateOptions(hostInfo, options);

        if (outputOkTag) {
            res.addData(new NoDataWrapper("ok"));
        }
    }

    @Required
    public void setServiceOptionsService(ServiceOptionsService serviceOptionsService) {
        this.serviceOptionsService = serviceOptionsService;
    }
}
