package com.wytehat.btlogger;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public final class NavigationHelper {
    private NavigationHelper() { }

    public static LinearLayout createBar(final Activity activity, final int page,
                                         String title) {
        LinearLayout bar = new LinearLayout(activity);
        bar.setOrientation(LinearLayout.HORIZONTAL);
        bar.setGravity(android.view.Gravity.CENTER_VERTICAL);
        bar.setPadding(dp(activity, 6), dp(activity, 5), dp(activity, 6), dp(activity, 5));
        bar.setBackgroundColor(Color.rgb(25, 63, 105));

        Button back = new Button(activity);
        back.setText("‹");
        back.setTextSize(24);
        bar.addView(back, new LinearLayout.LayoutParams(dp(activity, 56), dp(activity, 48)));

        TextView heading = new TextView(activity);
        heading.setText(title);
        heading.setTextColor(Color.WHITE);
        heading.setTextSize(20);
        heading.setGravity(android.view.Gravity.CENTER);
        heading.setTypeface(null, android.graphics.Typeface.BOLD);
        bar.addView(heading, new LinearLayout.LayoutParams(0, dp(activity, 48), 1));

        Button forward = new Button(activity);
        forward.setText("›");
        forward.setTextSize(24);
        bar.addView(forward, new LinearLayout.LayoutParams(dp(activity, 56), dp(activity, 48)));

        back.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) { navigate(activity, page - 1); }
        });
        forward.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) { navigate(activity, page + 1); }
        });
        return bar;
    }

    private static void navigate(Activity activity, int page) {
        Class<?> target;
        if (page == 0) target = MainActivity.class;
        else if (page == 1) target = DeviceManagerActivity.class;
        else if (page == 2) target = MapActivity.class;
        else {
            Toast.makeText(activity, page < 0 ? "This is the first view" :
                "This is the last view", Toast.LENGTH_SHORT).show();
            return;
        }
        if (target.equals(activity.getClass())) return;
        Intent intent = new Intent(activity, target);
        intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
        activity.startActivity(intent);
        activity.overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
    }

    private static int dp(Activity activity, int value) {
        return (int) (value * activity.getResources().getDisplayMetrics().density + 0.5f);
    }
}
