package com.company;
import example.proto.Mail;
import example.proto.Message;
import example.proto.ServerError;
import org.apache.avro.AvroRemoteException;
import org.apache.avro.AvroRuntimeException;
import org.apache.avro.ipc.NettyServer;
import org.apache.avro.ipc.NettyTransceiver;
import org.apache.avro.ipc.Server;
import org.apache.avro.ipc.specific.SpecificRequestor;
import org.apache.avro.ipc.specific.SpecificResponder;

import java.io.IOException;
import java.net.InetSocketAddress;

public class Main {

    public static class MailImpl implements Mail {
        // in this simple example just return details of the message
        public String send(Message message) throws org.apache.avro.AvroRemoteException {
            System.out.println("Sending message");
            //return new String("Sending message to " + message.getTo().toString()
            //        + " from " + message.getFrom().toString()
            //        + " with body " + message.getBody().toString());
            throw new ServerError("GGG");
        }

        @Override
        public boolean checkSpam(Message message) throws AvroRemoteException {
            System.out.println("Checking spam");
            return false;
        }
    }


    private static Server server;

    private static void startServer() throws IOException {
        server = new NettyServer(new SpecificResponder(Mail.class, new MailImpl()), new InetSocketAddress(65111));
        // the server implements the Mail protocol (MailImpl)
    }

    public static void main(String[] args) throws IOException {
        //if (args.length != 3) {
        //    System.out.println("Usage: <to> <from> <body>");
        //    System.exit(1);
        //}

        System.out.println("Starting server");
        // usually this would be another app, but for simplicity
        startServer();
        System.out.println("Server started");

        NettyTransceiver client = new NettyTransceiver(new InetSocketAddress(65111));
        // client code - attach to the server and send a message
        Mail proxy = (Mail) SpecificRequestor.getClient(Mail.class, client);
        System.out.println("Client built, got proxy");

        // fill in the Message record and send it
        Message message = new Message();
        message.setTo("Harry Potter");
        message.setFrom("Xiquet Aldeano");
        message.setBody("Ta mare quan pixa fa clotet?");
        System.out.println("Calling proxy.send with message:  " + message.toString());

        try {
            System.out.println("Result: " + proxy.send(message));
        } catch (AvroRemoteException e){
            e.printStackTrace();
        } catch (AvroRuntimeException e){
            e.printStackTrace();
        }

        System.out.print("Es Espam? " + proxy.checkSpam(message));

        // cleanup
        client.close();
        server.close();
    }
}
