package versao1;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;


public final class Cliente {

  public Cliente() {}

  public Cliente(String nome) {
    this.nome = nome;
  }

  private static final int UNSAVED = -1;

  private String nome;
  private long clienteId = UNSAVED;

  public void setClienteId(long clienteId) {
    this.clienteId = clienteId;
  }

  public long getClienteId() {
    return clienteId;
  }

  public void setNome(String nome) {
    this.nome = nome;
  }

  public String getNome() {
    return nome;
  }

  public void save() throws SQLException {
    if (getClienteId() == UNSAVED) {
      create();
    }
    else {
      update();
    }
  }

  private void create() throws SQLException {
    Connection conn = DBUtil.getConnection();
    PreparedStatement pstmt = conn.
        prepareStatement("INSERT INTO CLIENTE(NOME) VALUES (?)");
    pstmt.setString(1, getNome());
    pstmt.executeUpdate();
    ResultSet rs = pstmt.getGeneratedKeys();
    if (rs.next()) {
      setClienteId(rs.getLong(1));
    }
    conn.close();
  }

  private void update() throws SQLException {
    Connection conn = DBUtil.getConnection();
    PreparedStatement pstmt = conn.
        prepareStatement("UPDATE CLIENTE SET NOME = ? WHERE CLIENTEID = ?");
    pstmt.setString(1, getNome());
    pstmt.setLong(2, getClienteId());
    pstmt.executeUpdate();
    conn.close();
  }

  public void remove() throws SQLException {
    Pedido.removerPorCliente(this);
    Connection conn = DBUtil.getConnection();
    Statement stmt = conn.createStatement();
    stmt.executeUpdate("DELETE FROM CLIENTE WHERE CLIENTEID="+getClienteId());
    setClienteId(UNSAVED);
    conn.close();

  }

  public static void removerTodos() throws SQLException {
    Connection conn = DBUtil.getConnection();
    Statement stmt = conn.createStatement();
    stmt.executeUpdate("DELETE FROM ITEM");
    stmt.executeUpdate("DELETE FROM PEDIDO");
    stmt.executeUpdate("DELETE FROM CLIENTE");
    conn.close();
  }

  public static List buscarTodos() throws SQLException {
    List result = new ArrayList();
    Cliente cliente = null;

    Connection conn = DBUtil.getConnection();
    Statement stmt = conn.createStatement();
    ResultSet rs = stmt.executeQuery("SELECT * FROM CLIENTE");

    while (rs.next()) {
      cliente = new Cliente();
      cliente.setClienteId(rs.getLong("CLIENTEID"));
      cliente.setNome(rs.getString("NOME"));
      result.add(cliente);
    }
    conn.close();
    return result;

  }

}
