package de.lcs.wep.calendar;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.*;


/**
 * A resource is google's equivalent to a calendar
 */
public class Resource {

    public static Logger logger = LogManager.getLogger(Resource.class);

    public static Set<Resource> fromProperties(Properties props) {
        Set<Resource> resources = new HashSet<Resource>();
        try {
            // Filter properties - to avoid unsafe prop.size()-1 in for loop:
            Enumeration<?> keyEnum = props.propertyNames();
            while (keyEnum.hasMoreElements()) {
                String key = null;
                try {
                    key = keyEnum.nextElement().toString();
                    if (key.startsWith(Constants.RESOURCE_PROPERTY_PREFIX)) {
                        String resourceEmail = props.getProperty(key);
                        Resource resource = new Resource(resourceEmail);
                        resources.add(resource);
                    }
                } catch (Exception ex) {
                    logger.warn(key + " could not be read. Skipping resource.");
                }
            }
        } catch (Exception e) {
            logger.fatal("Resource events could not be fetched. Review prior log entries for more information.", e);
        }
        return resources;
    }

    private String id;
    private String name;
    private List<Event> events;

    public Resource(String id) {
        this.id = id;
        this.name = null;
        this.events = new ArrayList<Event>();
    }

    public String getID() {
        return id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void addEvent(Event event) {
        events.add(event);
    }

    public List<Event> getEvents() {
        return events;
    }

    @Override
    public String toString()
    {
        String raw = "id=%s, name=%s, events=%s";
        String result = String.format(raw, id, name, events);
        return result;
    }

}
