package de.duehl.swing.ui.start.card.b.work;

/*
 * Copyright 2016 Christian Dühl. All rights reserved.
 *
 * This program is free software. You can redistribute it and/or
 * modify it under the same terms as perl:
 *
 * general:  http://dev.perl.org/licenses/
 * GPL:      http://dev.perl.org/licenses/gpl1.html
 * artistic: http://dev.perl.org/licenses/artistic.html
 */

import de.duehl.swing.ui.layout.card.CardGui;
import de.duehl.swing.ui.layout.card.CardLogic;
import de.duehl.swing.ui.layout.card.CardResult;
import de.duehl.swing.ui.start.card.a.input.InputCardResult;

public class WorkCardLogic extends CardLogic {

    private static final Thread NOT_YET_STARTET = new Thread();

    private WorkCardGui gui;
    private WorkCardResult result;
    private InputCardResult previousResult;
    private Thread runningThread = NOT_YET_STARTET;
    private boolean interrupted = false;

    @Override
    public void setGui(CardGui gui) {
        if (gui instanceof WorkCardGui) {
            this.gui = (WorkCardGui) gui;
        }
        else {
            throw new RuntimeException("Aufruf mit der falschen Gui!");
        }
    }

    @Override
    public void setResultFromPreviousCard(CardResult previousResult) {
        if (previousResult instanceof InputCardResult) {
            this.previousResult = (InputCardResult) previousResult;
        }
        else {
            throw new RuntimeException("Aufruf mit dem falschen CardResult!");
        }
    }

    @Override
    public void runWhenShown() {
        int enteredValue = previousResult.getEnteredValue();
        boolean odd = enteredValue % 2 != 0;
        result = new WorkCardResult(odd);

        waitTwoSecondsBeforeGoOn();
    }

    synchronized private void waitTwoSecondsBeforeGoOn() {
        if (interrupted) {
            return;
        }

        runningThread = new Thread(new Runnable() {
            @Override
            public void run() {
                sleep(2); // Damit diese Karte überhaupt zu sehen ist...
                gui.done();
            }
        });
        runningThread.start();
    }

    private void sleep(int seconds) {
        long millis = 1000 * seconds;
        try {
            Thread.sleep(millis);
        }
        catch (InterruptedException e) {
            System.out.println("ICH WURDE UNTERBROCHEN!");
            //e.printStackTrace();
        }
    }

    @Override
    public CardResult getResult() {
        return result;
    }

    @Override
    synchronized public void quit() {
        interrupted = true;
        if (runningThread != NOT_YET_STARTET) {
            runningThread.interrupt();
        }
    }

}
