package com.publiccms.logic.component.workflow;

import java.io.IOException;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;

import com.publiccms.common.base.AbstractLongWorkflowHandler;
import com.publiccms.entities.cms.CmsPlace;
import com.publiccms.entities.sys.SysSite;
import com.publiccms.entities.sys.SysUser;
import com.publiccms.entities.sys.SysWorkflowProcess;
import com.publiccms.entities.sys.SysWorkflowProcessHistory;
import com.publiccms.logic.component.template.TemplateComponent;
import com.publiccms.logic.service.cms.CmsPlaceService;
import com.publiccms.logic.service.sys.SysWorkflowProcessService;

import freemarker.template.TemplateException;

@Component
public class PlaceWorkflowHandler extends AbstractLongWorkflowHandler {
    protected final Log log = LogFactory.getLog(getClass());
    @Resource
    private TemplateComponent templateComponent;

    @Override
    public String getItemType() {
        return SysWorkflowProcessService.ITEM_TYPE_PLACE;
    }

    @Override
    public void finish(SysSite site, SysWorkflowProcess entity, SysUser user, SysWorkflowProcessHistory history, Long itemId) {
        CmsPlace place = service.checkInProcess(entity.getSiteId(), user.getId(), itemId);
        try {
            templateComponent.publishPlace(site, place.getPath(), true);
        } catch (IOException | TemplateException e) {
            log.error(e.getMessage(), e);
        }
    }

    @Override
    public void interrupt(SysSite site, SysWorkflowProcess entity, SysUser user, SysWorkflowProcessHistory history, Long itemId) {
        service.rejectInProcess(entity.getSiteId(), user.getId(), itemId);
    }

    @Resource
    private CmsPlaceService service;
}
