/*
 * Copyright (C) 2010 Teleal GmbH, Switzerland
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.teleal.cling.model;

import org.teleal.cling.model.meta.LocalService;
import org.teleal.cling.model.state.ServiceState;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Christian Bauer
 */
public class DefaultServiceManager extends ServiceManager {

    final protected ServiceState state;
    final protected Class serviceClass;
    final ReentrantLock lock = new ReentrantLock(true);
    protected Object serviceImpl;

    public DefaultServiceManager(Class serviceClass) {
        this.serviceClass = serviceClass;
        this.state = new ServiceState();
    }

    public Class getServiceClass() {
        return serviceClass;
    }

    @Override
    public ServiceState getState() {
        return state;
    }

    @Override
    synchronized public Object getImplementation(LocalService service) throws Exception {
        if (serviceImpl == null) {
            serviceImpl = instantiateImplementation(service);
        }
        return serviceImpl;
    }

    protected Object instantiateImplementation(LocalService service) throws Exception {
        try {
            return serviceClass.getConstructor(LocalService.class).newInstance(service);
        } catch (NoSuchMethodException ex) {
            return getServiceClass().newInstance();
        }
    }

    public void executeLocked(Command cmd) throws Exception {
        try {
            if (lock.tryLock(500, TimeUnit.MILLISECONDS)) {
                cmd.execute();
            } else {
                throw new Exception("Could not aquire lock on service implementation, aborting execution");
            }
        } catch (InterruptedException ex) {
            throw new RuntimeException("Waiting for lock interrupted: " + ex.toString());
        } finally {
            if (lock.isLocked()) {
                lock.unlock();
            }
        }
    }
}
