/*
 * 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.thrift.sizing;

import java.io.FileOutputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.thrift.TException;
import org.apache.thrift.protocol.TCompactProtocol;
import org.apache.thrift.transport.TIOStreamTransport;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;

import com.ociweb.jnb.thrift.gen.Course;
import com.ociweb.jnb.thrift.gen.CourseNotFoundException;
import com.ociweb.jnb.thrift.gen.CourseService;

/**
 * This is a special server that spools a copy of
 * what is returned from the Thrift server to a file.
 */
public class OutputGrabber {
    
    private static final String HOST = "localhost";
    private static final int PORT = 8000;
    private static final int SOCKET_TIMEOUT = 1000;

    public static void main(String[] args) throws IOException, TTransportException {
        if (args.length != 1) {
            System.out.println("You must pass the location to store the file.");
            System.exit(1);
        }
        String location = args[0];
        
        int retcode = 0;
        final TSocket socket = new TSocket(HOST, PORT);
        socket.setTimeout(SOCKET_TIMEOUT);
//        final TTransport transport = socket;
        byte[] buff = new byte[10000];
        socket.open();
        final InputStreamGrabber streamGrabber = new InputStreamGrabber(socket.getSocket().getInputStream(), buff);
        final OutputStream socketOut = socket.getSocket().getOutputStream();
        final TTransport transport = new TIOStreamTransport(streamGrabber, socketOut);
        final TCompactProtocol protocol = new TCompactProtocol(transport);
        final CourseService.Client client = new CourseService.Client(protocol);
        
        try {
            transport.open();
            
            client.send_getCourse("DATABASE_101");
            Course course = client.recv_getCourse();
            System.out.println("Course = " + course);
        } catch (TException e) {
            e.printStackTrace(System.err);
            retcode = 1;
        } catch (RuntimeException e) {
            e.printStackTrace(System.err);
            retcode = 1;
        } catch (CourseNotFoundException e) {
            e.printStackTrace(System.err);
            retcode = 1;
        } finally {
            transport.close();
            
            FileOutputStream data = new FileOutputStream(location);
            data.write(buff, 0, streamGrabber.getCounter());
            data.close();
        }
        
        System.exit(retcode);
    }
    
    private static class InputStreamGrabber extends FilterInputStream {
        
        private byte[] buffer;
        private int counter;

        protected InputStreamGrabber(InputStream in, byte[] buffer) {
            super(in);
            
            this.buffer = buffer;
        }

        @Override
        public int read() throws IOException {
            int readByte = in.read();
            buffer[counter++] = (byte) readByte;
            return readByte;
        }

        @Override
        public int read(byte[] b, int off, int len) throws IOException {
            int readByteCount = in.read(b, off, len);
            
            for (int i = 0; i < readByteCount; i++) {
                buffer[counter++] = b[i + off];
            }
            
            return readByteCount;
        }

        public int getCounter() {
            return counter;
        }
        
        public void clear() {
            counter = 0;
        }
    }
}
