package de.frajul.endlessroll.main.screens;

import android.content.Context;
import android.widget.ViewFlipper;

/**
 * Created by Julian on 13.02.2016.
 */
public class ScreenFlipper extends ViewFlipper {

    private Screen[] screens;
    private Screen currentScreen;

    public ScreenFlipper(Context context, Screen... screens) {
        super(context);
        this.screens = screens;
        for (Screen screen : screens)
            addView(screen);
        currentScreen = screens[0];
        showScreen(currentScreen.getType(), Screen.ScreenType.NONE);
    }

    private void addView(Screen screen) {
        super.addView(screen.get(), screen.getType().getInFlipperPosition());
    }

    public Screen getCurrentScreen() {
        return currentScreen;
    }

    public void showScreen(Screen.ScreenType type, Screen.ScreenType caller) {
        Screen screen = findScreen(type);
        screen.setCaller(caller);
        screen.prepareToBeShown();

        int positionDifference = type.getInFlipperPosition() - currentScreen.getType().getInFlipperPosition();
        if (positionDifference < 0)
            for (; positionDifference != 0; positionDifference++)
                super.showPrevious();
        else if (positionDifference > 0)
            for (; positionDifference != 0; positionDifference--)
                super.showNext();
        currentScreen = screen;
    }

    private Screen findScreen(Screen.ScreenType type) {
        for (Screen screen : screens)
            if (screen.getType().equals(type)) {
                return screen;
            }
        return null;
    }

}
