package de.ctdo.bunti.control;

import java.util.Collection;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.stereotype.Component;

import de.ctdo.bunti.DeviceChangedEvent;
import de.ctdo.bunti.dao.BuntiDevicesDAO;
import de.ctdo.bunti.model.*;

@Component
public class BuntiControllerImpl implements BuntiController, ApplicationEventPublisherAware {
	private static final Logger LOGGER = LoggerFactory.getLogger(BuntiControllerImpl.class);
	private ApplicationEventPublisher applicationEventPublisher = null;
	private BuntiDevicesDAO devicesDAO;

	@Autowired
	public final void setDevicesDAO(BuntiDevicesDAO devicesDAO) {
		this.devicesDAO = devicesDAO;
	}

    @Override
    public final void setApplicationEventPublisher(ApplicationEventPublisher publisher) {
        this.applicationEventPublisher = publisher;
    }


    @Override
	public final boolean updateDeviceData(int deviceId, Map<String, Object> options) {
		BuntiDevice device = devicesDAO.getDeviceById(deviceId);
		
		if (device != null) {
			this.applicationEventPublisher.publishEvent(new DeviceChangedEvent(this, device, options));

            LOGGER.debug("publishEvent in BuntiController");
			return true;
		}

		return false;
	}

    @Override
    public Collection<BuntiDevice> getAllDevices() {
        return devicesDAO.getAllDevices();
    }

    @Override
    public BuntiDevice getDeviceById(int deviceId) {
        return devicesDAO.getDeviceById(deviceId);
    }

}
