package com.scrivenvar;
import static com.scrivenvar.Constants.*;
import static com.scrivenvar.Messages.get;
import com.scrivenvar.preferences.FilePreferencesFactory;
import com.scrivenvar.service.Options;
import com.scrivenvar.service.Snitch;
import com.scrivenvar.service.events.Notifier;
import com.scrivenvar.util.StageState;
import java.util.logging.LogManager;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.stage.Stage;
public final class Main extends Application {
private Options options;
private Snitch snitch;
private Thread snitchThread;
private static Application app;
private final MainWindow mainWindow = new MainWindow();
public static void main( final String[] args ) {
initLogger();
initPreferences();
launch( args );
}
private static void initLogger() {
LogManager.getLogManager().reset();
}
private static void initPreferences() {
System.setProperty(
"java.util.prefs.PreferencesFactory",
FilePreferencesFactory.class.getName()
);
}
@Override
public void start( final Stage stage ) throws Exception {
initApplication();
initNotifyService();
initState( stage );
initStage( stage );
initSnitch();
stage.show();
}
public static void showDocument( final String uri ) {
getApplication().getHostServices().showDocument( uri );
}
private void initApplication() {
app = this;
}
private void initNotifyService() {
final Notifier notifier = Services.load( Notifier.class );
notifier.addObserver( getMainWindow() );
}
private StageState initState( final Stage stage ) {
return new StageState( stage, getOptions().getState() );
}
private void initStage( final Stage stage ) {
stage.getIcons().addAll(
createImage( FILE_LOGO_16 ),
createImage( FILE_LOGO_32 ),
createImage( FILE_LOGO_128 ),
createImage( FILE_LOGO_256 ),
createImage( FILE_LOGO_512 ) );
stage.setTitle( getApplicationTitle() );
stage.setScene( getScene() );
}
private void initSnitch() {
setSnitchThread( new Thread( getSnitch() ) );
getSnitchThread().start();
}
@Override
public void stop() throws InterruptedException {
getSnitch().stop();
final Thread thread = getSnitchThread();
if( thread != null ) {
thread.interrupt();
thread.join();
}
}
private synchronized Snitch getSnitch() {
if( this.snitch == null ) {
this.snitch = Services.load( Snitch.class );
}
return this.snitch;
}
private Thread getSnitchThread() {
return this.snitchThread;
}
private void setSnitchThread( final Thread thread ) {
this.snitchThread = thread;
}
private synchronized Options getOptions() {
if( this.options == null ) {
this.options = Services.load( Options.class );
}
return this.options;
}
private Scene getScene() {
return getMainWindow().getScene();
}
private MainWindow getMainWindow() {
return this.mainWindow;
}
private String getApplicationTitle() {
return get( "Main.title" );
}
private static Application getApplication() {
return app;
}
private Image createImage( final String filename ) {
return new Image( filename );
}
}