/*
 * Copyright 2009 Andrew Prunicki <prunand@iit.edu,prunicki@ociweb.com>
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.ociweb.jnb.rmi;

import java.io.IOException;
import java.rmi.AlreadyBoundException;
import java.rmi.NotBoundException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.util.List;

import com.ociweb.jnb.db.Course;
import com.ociweb.jnb.db.Database;

public class RmiServer {
    
    public static final int PORT = 8081;
    public static final String SERVICE_NAME = "CourseService";
    private static Database db = new Database();

    public static void main(final String[] args) {
        if (args.length < 1) {
            System.out.println("Hostname must be passed");
            System.exit(1);
        }
        final String hostName = args[0];
        System.setProperty("java.rmi.server.hostname", hostName);
        
        final CourseService svcImpl = new DefaultCourseService();
        try {
            final CourseService stub = (CourseService) UnicastRemoteObject.exportObject(svcImpl, 0);
            final Registry registry = LocateRegistry.createRegistry(PORT);
            
            System.out.println("Firing up the RMI server. - Press <Enter> to terminate.");
            registry.bind(SERVICE_NAME, stub);
            System.in.read();
            registry.unbind(SERVICE_NAME);
            System.exit(0);
        } catch (AlreadyBoundException e) {
            e.printStackTrace(System.err);
            System.exit(1);
        } catch (NotBoundException e) {
            e.printStackTrace(System.err);
            System.exit(1);
        } catch (IOException e) {
            e.printStackTrace(System.err);
            System.exit(1);
        }
    }
    
    private static class DefaultCourseService implements CourseService {

        @Override
        public List<String> getCourseInventory() {
            return db.getCourseList();
        }

        @Override
        public Course getCourse(String number) {
            return db.getCourse(number);
        }

        @Override
        public void addCourse(Course course) {
            if (course != null) {
                db.addCourse(course);
            }
        }

        @Override
        public void deleteCourse(String number) {
            db.deleteCourse(number);
        }
    }
}
