
/*
 *  Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
*/
package com.sun.bookstore.database;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

import com.sun.bookstore.database.Book;

public class BooksSetup {

private static final String PERSISTENCE_UNIT_NAME = "book";
  private static EntityManagerFactory factory;

  public static void setUp() throws Exception {
    Book book = null;
    factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
    EntityManager em = factory.createEntityManager();

    // Begin a new local transaction so that we can persist a new entity
    em.getTransaction().begin();

    // Read the existing entries
    Query q = em.createQuery("select m from Book m");
    // Books should be empty

    // Do we have entries?
    boolean createNewEntries = (q.getResultList().size() == 0);
    System.out.println("->-->-> BooksSetup.setUp(): createNewEntries = " + createNewEntries);
    // No, so lets create new entries
    if (createNewEntries) {
      System.out.println("->-->-> BooksSetup.setUp(): adding books");
      book = new Book("201", "Duke", "", "My Early Years: Growing up on *7", 30.75f, false, 1995, "What a cool book.", 20); em.persist(book);
      book = new Book("202", "Jeeves", "", "Web Servers for Fun and Profit", 40.75f, true, 2000, "What a cool book.", 20); em.persist(book);
      book = new Book("203", "Masterson", "Webster", "Web Components for Web Developers", 27.75f, false, 2000, "What a cool book.", 20); em.persist(book);
      book = new Book("205", "Novation", "Kevin", "From Oak to Java: The Revolution of a Language", 10.75f, true, 1998, "What a cool book.", 20); em.persist(book);
      book = new Book("206", "Gosling", "James", "Java Intermediate Bytecodes", 30.95f, true, 2000, "What a cool book.", 20); em.persist(book);
      book = new Book("207", "Thrilled", "Ben", "The Green Project: Programming for Consumer Devices", 30.00f, true, 1998, "What a cool book", 20); em.persist(book);
      book = new Book("208", "Tru", "Itzal", "Duke: A Biography of the Java Evangelist", 45.00f, false, 2001, "What a cool book.", 20); em.persist(book);
    }

    // Commit the transaction, which will cause the entities to
    // be stored in the database
    em.getTransaction().commit();

    // It is always good practice to close the EntityManager so that
    // resources are conserved.
    em.close();
  }
}