/*
 * Copyright (c) 2015. Capiot Software India Pvt Ltd.
 * Author: ajit@capiot.com
 */

package com.capiot.analytics.spark.stream;

import org.apache.spark.storage.StorageLevel;
import org.apache.spark.streaming.receiver.Receiver;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.ConnectException;
import java.net.Socket;
import java.util.concurrent.atomic.AtomicInteger;

public class SparkCustomSocketReceiver extends Receiver<String>
{
    private String host;
    private int port = -1;

    public SparkCustomSocketReceiver(String host, int port)
    {
        super(StorageLevel.MEMORY_AND_DISK_SER_2());
        this.host = host;
        this.port = port;
    }

    public void onStart()
    {
        // Start the thread that receives data over a connection
        new Thread()
        {
            @Override
            public void run()
            {
                receive();
            }
        }.start();
    }

    public void onStop()
    {
        // There is nothing much to do as the thread calling receive()
        // is designed to stop by itself isStopped() returns false
    }

    /**
     * Create a socket connection and receive data until receiver is stopped
     */
    private void receive()
    {
        Socket socket = null;
        String userInput = null;
        AtomicInteger ai = new AtomicInteger(0);
        try
        {
            // connect to the server
            socket = new Socket(host, port);

            BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            // Until stopped or connection broken continue reading
            while (!isStopped() && (userInput = reader.readLine()) != null)
            {
                System.out.println("Received line as '" + userInput + "'");
                store(userInput);
                ai.getAndIncrement();
            }

            System.out.println("============Stored lines in Spark:count:"+ ai.toString() );
            reader.close();
            socket.close();

            // Restart in an attempt to connect again when server is active again
            restart("++++++++++++++ Trying to connect again");
        }
        catch (ConnectException ce)
        {
            // restart if could not connect to server
            //restart("Could not connect", ce);
            ce.printStackTrace();
        }
        catch (Throwable t)
        {
            //restart("Error receiving data", t);
            t.printStackTrace();
        }
    }
}