package org.bucksch.zeipis.all;
import org.bucksch.zeipis.recorder.*;
import org.bucksch.zeipis.store.*;
import java.sql.*;
import java.util.Map;


/**
 * Data needed by all or several server parts (Core, Recorder, Store etc.)
 * @author ben
 */
public class CoreData
{
  public CoreData()
    throws SQLException, Misconfiguration
  {
    me = this;
    if (DB.me == null)
      new DB();
    setup();
  }
  protected void setup()
    throws SQLException, Misconfiguration
  {
    // Devices
    ResultSet rs;
    PreparedStatement findDevices = DB.me.database().prepareStatement("SELECT * FROM device WHERE devicetype = ?");
    findDevices.setString(1, "DVB");
    rs = findDevices.executeQuery();
    while (rs.next())
    {
      int id = rs.getInt("deviceid");
      try {
        myCards.put(id, new DVBCard(id));
      } catch (Exception e) {
        Util.error(e);
      }
    }

    // DVB Transponders
    PreparedStatement findTransponders = DB.me.database().prepareStatement("SELECT * FROM dvb_transponder");
    rs = findTransponders.executeQuery();
    while (rs.next())
    {
      //try {
        int id = rs.getInt("dvb_transponderid");
        myDVBTransponders.put(id, DVBTransponder.createFromDatabase(rs));
      //} catch (Exception e) { Util.error(e); }
    }

    // Channels
    PreparedStatement findChannels = DB.me.database().prepareStatement("SELECT * FROM channel WHERE channeltype = 'DVB'");
    rs = findChannels.executeQuery();
    while (rs.next())
    {
      //try {
        int id = rs.getInt("channelid");
        myChannels.put(id, new DVBChannel(id));
      //} catch (Exception e) { Util.error(e); }
    }

    // Stores
    PreparedStatement findStores = DB.me.database().prepareStatement("SELECT * FROM store");
    rs = findStores.executeQuery();
    while (rs.next())
    {
      String name = rs.getString("storename");
      String host = rs.getString("host");
      Store store;
      if (Util.isThisHost(host))
        store = new LocalStore(name);
      else
        store = new RemoteStore(host, name);
      myStores.put(name, store);
    }
  }

  // Data
  public static CoreData me = null;
  public Map<Integer, DVBTransponder> myDVBTransponders = Util.newMap(); // key = id
  public Map<Integer, TVChannel> myChannels = Util.newMap(); // key = id
  public Map<Integer, TVCard> myCards = Util.newMap(); // key = id
  public Map<String, Store> myStores = Util.newMap(); // key = store name
}
