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.Date;
import java.util.Iterator;
import java.util.List;

public final class Pedido {
  private static final int UNSAVED=-1;

  private long pedidoId = UNSAVED;
  private Date dataEmissao;

  /**
   * @label cliente
   */
  private Cliente cliente;
  private List /*ItemPedido*/ itens = new ArrayList();

  /**
   * @link aggregationByValue
   * @label Itens
   * @directed 
   */
  private ItemPedido lnkItemPedido;

  public Pedido() {}

  public List getItems() {
    return itens;
  }

  public Date getDataEmissao() {
    return dataEmissao;
  }

  public void setPedidoId(long pedidoId) {
    this.pedidoId = pedidoId;
  }

  public void setItems(List items) {
    this.itens= items;
  }

  public void setDataEmissao(Date dataEmissao) {
    this.dataEmissao = dataEmissao;
  }

  public long getPedidoId() {
    return pedidoId;
  }

  public Cliente getCliente() {
    return cliente;
  }

  public void setCliente(Cliente cliente) {
    this.cliente = cliente;
  }

  public Pedido(Date dataEmissao, Cliente cliente) {
    this.dataEmissao = dataEmissao;
    this.cliente = cliente;
  }

  public boolean validate() {
    return cliente != null;
  }

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

  /** Metodos de acesso a dados **/
  private void create() throws SQLException {
    if (!validate()) {
      throw new IllegalStateException("BUG: Estado do objeto ilegal.");
    }
    Connection conn = DBUtil.getConnection();
    PreparedStatement pstmt = conn.prepareStatement(
        "INSERT INTO PEDIDO (DATAEMISSAO,CLIENTEID) VALUES (?,?)");
    pstmt.setDate(1, new java.sql.Date(getDataEmissao().getTime()));
    pstmt.setLong(2, cliente.getClienteId());
    pstmt.executeUpdate();
    ResultSet rs = pstmt.getGeneratedKeys();
    if (rs.next()) {
      setPedidoId(rs.getLong(1));
    }
    atualizarItems();
    conn.close();
  }

  private void update() throws SQLException{
    Connection conn = DBUtil.getConnection();
    PreparedStatement pstmt = conn.prepareStatement(
        "UPDATE PEDIDO SET CLIENTEID=?,DATAEMISSAO=? WHERE PEDIDOID=?"
        );
    pstmt.setLong(1,getCliente().getClienteId());
    pstmt.setDate(2,new java.sql.Date(getDataEmissao().getTime()));
    pstmt.setLong(3,getPedidoId());
    pstmt.execute();
    conn.close();
  }

  public static List /*Pedido*/ buscarPorCliente(Cliente cliente) throws
      SQLException {
    Pedido pedido = null;
    List result = new ArrayList();

    Connection conn = DBUtil.getConnection();
    Statement stmt = conn.createStatement();
    ResultSet rs = stmt.executeQuery("SELECT * FROM PEDIDO WHERE CLIENTEID = " +
                                     cliente.getClienteId());
    while (rs.next()) {
      pedido = new Pedido();
      pedido.setCliente(cliente);
      pedido.setPedidoId(rs.getLong("PEDIDOID"));
      pedido.setDataEmissao(rs.getDate("DATAEMISSAO"));
      pedido.carregarItems();
      result.add(pedido);
    }
    conn.close();
    return result;
  }

  public static void removerPorCliente(Cliente cliente) throws SQLException {
    Connection conn = DBUtil.getConnection();
  Statement stmt = conn.createStatement();
  stmt.executeUpdate("DELETE FROM PEDIDO WHERE CLIENTEID = " + cliente.getClienteId());
  conn.close();

  }

  private void atualizarItems() throws SQLException{
    removerItems();
    salvarItems();
  }

  private void carregarItems() throws SQLException {
    List/*ItemPedido*/ result = new ArrayList();
    ItemPedido item = null;

    Connection conn = DBUtil.getConnection();
    Statement stmt = conn.createStatement();
    ResultSet rs = stmt.executeQuery("SELECT * FROM ITEM WHERE PEDIDOID =" +
                                     getPedidoId());
    while (rs.next()) {
      item = new ItemPedido();
      item.setItem(rs.getString("ITEM"));
      item.setQuatidade(rs.getInt("QUANTIDADE"));
      item.setPrecoUn(rs.getFloat("VALOR"));
      result.add(item);
    }
    setItems(result);
  }

  private void removerItems() throws SQLException {
    Connection conn = DBUtil.getConnection();
    Statement stmt = conn.createStatement();
    stmt.executeUpdate("DELETE FROM ITEM WHERE PEDIDOID = "+getPedidoId());
    conn.close();

  }

  private void salvarItems() throws SQLException {
    Connection conn = DBUtil.getConnection();
    PreparedStatement pstmt = conn.prepareStatement(
        "INSERT INTO ITEM (PEDIDOID,ITEM,QUANTIDADE,VALOR) VALUES (?,?,?,?)");
    pstmt.setLong(1,getPedidoId());
    for (Iterator iter = getItems().iterator(); iter.hasNext(); ) {
      ItemPedido item = (ItemPedido)iter.next();
      pstmt.setString(2,item.getItem());
      pstmt.setInt(3,item.getQuatidade());
      pstmt.setFloat(4,item.getPrecoUn());
      pstmt.executeUpdate();
    }
  }


}
