package dao.ex3;

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

import dao.DAO;
import dao.Student;

public class Dao3 implements DAO<Long, Student> {

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

  private void openConnection(String host, int port) {
    try {
      socket = new Socket(host, port);
      out = new ObjectOutputStream(socket.getOutputStream());
      in = new ObjectInputStream(socket.getInputStream());
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  private void closeConnection() {
    try {
      socket.close();
      out.close();
      in.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public Student get(Long key) {
    Student s = null;
    try {
      this.openConnection("localhost", 4444);
      out.writeObject(new Integer(DAO.GET));
      out.writeObject(new Long(key));
      s = (Student) in.readObject();
      out.writeObject(new Integer(EOF));
      this.closeConnection();
    } catch (Exception e) {
      e.printStackTrace();
    }
    return s;
  }

  public void add(Long key, Student value) {
    try {
      this.openConnection("localhost", 4444);
      out.writeObject(new Integer(DAO.ADD));
      out.writeObject(new Long(key));
      out.writeObject(value);
      out.writeObject(new Integer(EOF));
      this.closeConnection();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public void update(Long key, Student value) {
    try {
      this.openConnection("localhost", 4444);
      out.writeObject(new Integer(DAO.UPDATE));
      out.writeObject(new Long(key));
      out.writeObject(value);
      out.writeObject(new Integer(EOF));
      this.closeConnection();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public void delete(Long key) {
    try {
      this.openConnection("localhost", 4444);
      out.writeObject(new Integer(DAO.DELETE));
      out.writeObject(new Long(key));
      out.writeObject(new Integer(EOF));
      this.closeConnection();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public static void main(String args[]) {
    System.out.println("Running the client 3");
    Dao3 d = new Dao3();
    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);
  }

}
