package ru.yandex.webmaster.periodic;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import ru.yandex.common.framework.core.ServRequest;
import ru.yandex.common.framework.core.ServResponse;
import ru.yandex.common.framework.http.HttpServResponse;
import ru.yandex.common.scheduler.TaskExecutor;
import ru.yandex.wmtools.common.error.InternalException;
import ru.yandex.wmtools.common.error.UserException;
import ru.yandex.wmtools.common.servantlet.AbstractServantlet;

/**
 * @author aherman
 */
public class RunTaskServantlet extends AbstractServantlet implements ApplicationContextAware {
    private ApplicationContext applicationContext;

    @Override
    protected void doProcess(ServRequest req, ServResponse res) throws UserException, InternalException {
        String taskId = req.getParam("task-bean-id");
        if (StringUtils.isEmpty(taskId)) {
            ((HttpServResponse)res).setHttpStatusCode(500);
            res.addData("No task-bean-id");
            return;
        }

        Object bean = applicationContext.getBean(taskId);
        if (!(bean instanceof TaskExecutor)) {
            ((HttpServResponse)res).setHttpStatusCode(500);
            res.addData("Unexpected bean type: " + bean.getClass().getSimpleName());
            return;
        }

        String result = ((TaskExecutor) bean).run(null);
        ((HttpServResponse)res).setHttpStatusCode(200);
        res.addData("Result: " + result);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
