/**
 *  Copyright © 2025, Luis Andrés Lange <https://javacomm.net>
 *
 *  Previously released under Apache License 2.0; now licensed under MPL 2.0.
 *
 *  This Source Code Form is subject to the terms of the Mozilla Public
 *  License, v. 2.0. If a copy of the MPL was not distributed with this
 *  file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 *  ----------------------------------------------------------------------------
 *
 *  Exhibit B - "Incompatible With Secondary Licenses" Notice
 *
 *  This Source Code Form is "Incompatible With Secondary Licenses",
 *  as defined by the Mozilla Public License, v. 2.0.
 *
 *  In short:
 *  - This file may be used, modified, and distributed under MPL 2.0 only.
 *  - It may NOT be relicensed under GPL, LGPL, AGPL, or any other Secondary License.
 *
 *  Rationale:
 *  - Ensures that the code remains MPL-2.0.
 *  - Avoids legal conflicts with GPL-licensed libraries (e.g., VideoLAN).
 *  - Maximizes usability for commercial and security-critical applications.
 *
 */
package net.javacomm.server;

import jakarta.xml.bind.JAXBException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.xml.sax.SAXException;
import net.javacomm.database.DatabaseServiceImpl;
import net.javacomm.database.PoolException;
import net.javacomm.facade.DatabaseService;
import net.javacomm.facade.Server;



public class ServerImpl implements Runnable, Server {

  private final static Logger log = LogManager.getLogger(ServerImpl.class);
  private static Server instance;
  private DatabaseService database;
  private boolean semaphor = false;
  private Thread thread;

  private ServerImpl() {
    database = DatabaseServiceImpl.getInstance();
    try {
      database.connect();
    }
    catch (SAXException | JAXBException | PoolException e) {
      log.fatal(e.getMessage(), e.getCause());
      throw new RuntimeException(e.getMessage(), e.getCause());
    }
  }

  static {
    instance = new ServerImpl();
  }

  public synchronized static Server getInstance() {
    return instance;
  }



  /**
   * Der Server wird gestartet.
   */
  @Override
  public void execute() {
    if (semaphor) {
      log.info("Server is already running....");
      return;
    }
    semaphor = true;
    thread = new Thread(ServerImpl.this);
    thread.start();
  }



  @Override
  public void run() {
    log.info("Crusaders Daemon has started");
    log.info("(C) 2001 www.nexuswob.org, written by Luis Andrés Lange");
    log.info("waiting for incoming clients on port " + "49157" + "....");
    while (semaphor) {
      try {
        Thread.sleep(20000);
      }
      catch (InterruptedException e) {}
      semaphor = false;
    }
  }

}
