package com.lemenzo.clock.bedtime;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.Gravity;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.lemenzo.clock.R;
import com.lemenzo.clock.util.Ui;

public final class BedtimeSunriseActivity extends Activity {
    private static final long DURATION_MS = 15L * 60_000L;
    private final Handler h = new Handler(Looper.getMainLooper());
    private long started;
    private SunriseView sunrise;

    private final Runnable fade = new Runnable() {
        @Override public void run() {
            float p = Math.min(1f, (System.currentTimeMillis() - started) / (float) DURATION_MS);
            sunrise.setProgress(p);
            WindowManager.LayoutParams lp = getWindow().getAttributes();
            lp.screenBrightness = .03f + .67f * p;
            getWindow().setAttributes(lp);
            if (p < 1f) h.postDelayed(this, 1000L);
        }
    };

    @Override protected void onCreate(Bundle b) {
        super.onCreate(b);
        setShowWhenLocked(true);
        setTurnScreenOn(true);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        started = System.currentTimeMillis();

        FrameLayout root = new FrameLayout(this);
        sunrise = new SunriseView(this);
        root.addView(sunrise, new FrameLayout.LayoutParams(-1, -1));

        LinearLayout content = new LinearLayout(this);
        content.setOrientation(LinearLayout.VERTICAL);
        content.setGravity(Gravity.CENTER);
        content.setPadding(Ui.dp(this, 28), Ui.dp(this, 36), Ui.dp(this, 28), Ui.dp(this, 36));
        TextView title = Ui.title(this, getString(R.string.sunrise_title), 42);
        title.setGravity(Gravity.CENTER);
        title.setShadowLayer(10f, 0f, 2f, 0xaa000000);
        content.addView(title);
        TextView sub = Ui.text(this, getString(R.string.sunrise_subtitle), 17, Color.WHITE);
        sub.setGravity(Gravity.CENTER);
        sub.setShadowLayer(8f, 0f, 2f, 0xaa000000);
        content.addView(sub);
        root.addView(content, new FrameLayout.LayoutParams(-1, -1));

        setContentView(root);Ui.applySystemSafeInsets(this,root);
        h.post(fade);
    }

    @Override protected void onDestroy() {
        h.removeCallbacksAndMessages(null);
        super.onDestroy();
    }
}
