package com.wasu.cs.widget;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.view.View;

/**
 * Manages the visibility of a view, with optional animations.
 */
public class VisibilityController {

    private final View mView;
    private final int mAnimationDuration;
    private boolean mVisible;

    VisibilityController(View view) {
        mView = view;
		mAnimationDuration = 100;
        mVisible = view.getVisibility() == View.VISIBLE;
    }

    boolean isVisible() {
        return mVisible;
    }
    boolean setVisible(final boolean visible, boolean animated) {
        if (isVisible() == visible) {
            return false;
        }
        mVisible = visible;
        if (animated) {
            float toAlpha = visible ? 1.0f : 0.0f;
            ObjectAnimator mAnimator = ObjectAnimator.ofFloat(mView, "Alpha", 1-toAlpha, toAlpha);
            mAnimator.setDuration(mAnimationDuration).
                addListener(new AnimatorListenerAdapter() {

                @Override
                public void onAnimationStart(Animator animator) {
                    if (visible) {
                        setViewVisible(true);
                    }
                }

                @Override
                public void onAnimationEnd(Animator animator) {
                    if (!visible) {
                        setViewVisible(false);
                    }
                }
            });
            mAnimator.start();
        } else {
            setViewVisible(visible);
        }
        return true;
    }

    private void setViewVisible(boolean visible) {
        mView.setVisibility(visible ? View.VISIBLE : View.GONE);
    }
}

