/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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 org.apache.airavata.api.server;

import org.apache.airavata.api.Airavata;
import org.apache.airavata.api.error.AiravataErrorType;
import org.apache.airavata.api.error.AiravataSystemException;
import org.apache.airavata.api.server.handler.AiravataServerHandler;
import org.apache.airavata.api.server.util.RegistryInitUtil;
import org.apache.airavata.common.utils.AiravataUtils;
import org.apache.airavata.common.utils.IServer;
import org.apache.thrift.server.TServer;
import org.apache.thrift.server.TSimpleServer;
import org.apache.thrift.transport.TServerSocket;
import org.apache.thrift.transport.TServerTransport;
import org.apache.thrift.transport.TTransportException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class AiravataAPIServer implements IServer{

    private final static Logger logger = LoggerFactory.getLogger(AiravataAPIServer.class);

    //FIXME: Read the port from airavata-server.config file
    private static final int THRIFT_SERVER_PORT = 8930;
    private ServerStatus status;

	private TSimpleServer server;

	public AiravataAPIServer() {
		setStatus(ServerStatus.STOPPED);
	}
	
    public void StartAiravataServer(Airavata.Processor<AiravataServerHandler> mockAiravataServer) throws AiravataSystemException {
        try {
            AiravataUtils.setExecutionAsServer();
            RegistryInitUtil.initializeDB();
            TServerTransport serverTransport = new TServerSocket(THRIFT_SERVER_PORT);
            server = new TSimpleServer(
                    new TServer.Args(serverTransport).processor(mockAiravataServer));
            logger.info("Starting Airavata Mock Airavata Server on Port " + THRIFT_SERVER_PORT);
            logger.info("Listening to Airavata Clients ....");
            new Thread() {
				public void run() {
					server.serve();
					RegistryInitUtil.stopDerbyInServerMode();
				}
			}.start();
			setStatus(ServerStatus.STARTED);
        } catch (TTransportException e) {
            logger.error(e.getMessage());
            setStatus(ServerStatus.FAILED);
            RegistryInitUtil.stopDerbyInServerMode();
            throw new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR);
        }
    }

    public static void main(String[] args) {
    	try {
			AiravataAPIServer server = new AiravataAPIServer();
			server.start();
//			System.out.println(server.getStatus()+":"+server.getStatus().getTime());
//			Thread.sleep(3000);
//			server.stop();
//			System.out.println(server.getStatus()+":"+server.getStatus().getTime());
//			Thread.sleep(3000);
//			server.start();
//			System.out.println(server.getStatus()+":"+server.getStatus().getTime());
//			Thread.sleep(3000);
//			server.stop();
		} catch (Exception e) {
			e.printStackTrace();
		}
    }

	@Override
	public void start() throws Exception {
		setStatus(ServerStatus.STARTING);
		Airavata.Processor<AiravataServerHandler> mockAiravataServer =
                new Airavata.Processor<AiravataServerHandler>(new AiravataServerHandler());
    	StartAiravataServer(mockAiravataServer);
	}

	@Override
	public void stop() throws Exception {
		if (server.isServing()){
			server.stop();
			setStatus(ServerStatus.STOPPED);
			logger.info("Airavata API Server Stopped.");
		}
		
	}

	@Override
	public void restart() throws Exception {
		stop();
		start();
	}

	@Override
	public void configure() throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public ServerStatus getStatus() throws Exception {
		return status;
	}
	
	private void setStatus(ServerStatus stat){
		status=stat;
		status.updateTime();
	}
}

@@ -1234,32 +1234,88 @@
 .utils.IServer;%0A
+import org.apache.airavata.common.utils.ServerSettings;%0A
 import org.apach
@@ -1331,32 +1331,32 @@
 server.TServer;%0A
-
 import org.apach
@@ -1832,19 +1832,22 @@
 c final 
+Str
 in
-t
+g
  THRIFT_
@@ -1864,12 +1864,31 @@
 T = 
-8930
+%22apiserver.server.port%22
 ;%0A  
@@ -2326,16 +2326,59 @@
 rSocket(
+Integer.parseInt(ServerSettings.getSetting(
 THRIFT_S
@@ -2379,32 +2379,41 @@
 RIFT_SERVER_PORT
+,%228930%22))
 );%0A            s
@@ -2800,24 +2800,112 @@
 rverMode();%0A
+%09%09%09%09%09setStatus(ServerStatus.STOPPED);%0A%09%09%09%09%09logger.info(%22Airavata API Server Stopped.%22);%0A
 %09%09%09%09%7D%0A%09%09%09%7D.s
@@ -3362,378 +3362,8 @@
 ();%0A
-//%09%09%09System.out.println(server.getStatus()+%22:%22+server.getStatus().getTime());%0A//%09%09%09Thread.sleep(3000);%0A//%09%09%09server.stop();%0A//%09%09%09System.out.println(server.getStatus()+%22:%22+server.getStatus().getTime());%0A//%09%09%09Thread.sleep(3000);%0A//%09%09%09server.start();%0A//%09%09%09System.out.println(server.getStatus()+%22:%22+server.getStatus().getTime());%0A//%09%09%09Thread.sleep(3000);%0A//%09%09%09server.stop();%0A
 %09%09%7D 
@@ -3790,16 +3790,16 @@
 ing())%7B%0A
+
 %09%09%09serve
@@ -3812,92 +3812,8 @@
 ();%0A
-%09%09%09setStatus(ServerStatus.STOPPED);%0A%09%09%09logger.info(%22Airavata API Server Stopped.%22);%0A
 %09%09%7D%0A

refactor to read the port from config file