package dao.ex5;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

import dao.DAO;
import dao.Student;

public class Dao5 implements DAO<Long, Student> {

  private ObjectOutputStream out;
  private ObjectInputStream in;
  private static final int EOF = -1;

  public Dao5(ObjectOutputStream out, ObjectInputStream in) {
    this.out = out;
    this.in = in;
  }

  public Student get(Long key) {
    Student s = null;
    try {
      out.writeObject(new Integer(DAO.GET));
      out.writeObject(new Long(key));
      s = (Student) in.readObject();
      out.flush();
    } catch (Exception e) {
      e.printStackTrace();
    }
    return s;
  }

  public void add(Long key, Student value) {
    try {
      out.writeObject(new Integer(DAO.ADD));
      out.writeObject(new Long(key));
      out.writeObject(value);
      out.flush();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public void update(Long key, Student value) {
    try {
      out.writeObject(new Integer(DAO.UPDATE));
      out.writeObject(new Long(key));
      out.writeObject(value);
      out.flush();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public void delete(Long key) {
    try {
      out.writeObject(new Integer(DAO.DELETE));
      out.writeObject(new Long(key));
      out.flush();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public static void main(String args[]) {
    System.out.println("Running the client 5");

    Socket socket = null;
    ObjectOutputStream out = null;
    ObjectInputStream in = null;

    // Open a new connection:
    try {
      socket = new Socket("localhost", 4444);
      out = new ObjectOutputStream(socket.getOutputStream());
      in = new ObjectInputStream(socket.getInputStream());
    } catch (Exception e) {
      e.printStackTrace();
    }

    // Create the DAO
    Dao5 d = new Dao5(out, in);

    // Execute the DAO operations
    Student s = d.get(200934878L);
    System.out.println(s);
    d.add(160355385L, new Student(160355385L, "Caravaggio", 98.0));
    s = d.get(160355385L);
    System.out.println(s);
    d.update(160355385L, new Student(160355385L, "Michelangelo Merisi", 99.5));
    s = d.get(160355385L);
    System.out.println(s);

    // Close the connection:
    try {
      out.writeObject(new Integer(EOF));
      out.flush();
      socket.close();
      out.close();
      in.close();
    } catch (Exception e) {
      e.printStackTrace();
    }

  }

}
