package com.algobase.share.dialog;

import android.os.Bundle;
import android.os.Build;
import android.os.Handler;

import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Configuration;
import android.content.res.Resources;

import android.view.Gravity;

import android.view.View;
import android.view.ViewGroup;
import android.view.MotionEvent;
import android.view.LayoutInflater;
import android.view.ContextThemeWrapper;
import android.view.WindowManager;
import android.view.Window;
import android.view.Display;
import android.view.inputmethod.InputMethodManager;

import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.Toast;
import android.widget.TextView;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.BaseAdapter;
import android.widget.ListAdapter;
import android.widget.ArrayAdapter;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.RadioButton;
import android.widget.CheckBox;
import android.widget.SeekBar;
import android.widget.ProgressBar;

import android.app.Dialog;
import android.app.AlertDialog;

import android.app.Activity;
import android.app.DialogFragment;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;

/*
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
*/


import android.graphics.Paint;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.ClipDrawable;
import android.graphics.drawable.shapes.RectShape;

import com.algobase.share.compat.*;

public class MyDialogFragment extends DialogFragment {

  static int BACKGROUND_COLOR_LIGHT = 0xffffffff;
//static int BACKGROUND_COLOR_DARK = 0xff333333;
  static int BACKGROUND_COLOR_DARK = 0xff303030;

//public static int TITLE_TEXT_COLOR_LIGHT = 0xff0099cc;
  public static int TITLE_TEXT_COLOR_LIGHT = 0xff0077cc;

//public static int TITLE_TEXT_COLOR_DARK = 0xff80d0ff;
  public static int TITLE_TEXT_COLOR_DARK = 0xffffffff;


  public static int TITLE_TEXT_SIZE = 25;
  public static int MESSAGE_TEXT_SIZE = 18;
                                  
  public static int STYLE_TRADITIONAL   = 0;
  public static int STYLE_HOLO_DARK     = 1;
  public static int STYLE_HOLO_LIGHT    = 2;
  public static int STYLE_MATERIAL_DARK  = 3;
  public static int STYLE_MATERIAL_LIGHT = 4;


  public static int[] dialog_styles = { 
                          StyleCompat.Theme_Traditional,
                          StyleCompat.Theme_Holo,
                          StyleCompat.Theme_Holo_Light,
                          StyleCompat.Theme_Material,
                          StyleCompat.Theme_Material_Light
                        };

  public static int def_anim_style = 0;

//public static int def_style = STYLE_MATERIAL_DARK;
  public static int def_style = STYLE_HOLO_LIGHT;

  public static void setStyle(int i) { def_style = i; }
  public static int getStyle() { return def_style; }


  public static void setDefAnimationStyle(int r) { def_anim_style = r; }

  public static Context wrapContext(Context ctxt) { 
    return new ContextThemeWrapper(ctxt,dialog_styles[def_style]);
  }


  private static int global_title_button_left_img = 0;

  public static void setGlobalTitleButtonLeft(int r) {  
       global_title_button_left_img = r; 
  }

  boolean dark_mode() {
     return (style == STYLE_HOLO_DARK || style == STYLE_MATERIAL_DARK);
  }

  boolean holo() {
     return (style == STYLE_HOLO_DARK || style == STYLE_HOLO_LIGHT);
  }


  int style = def_style;
  int anim_style = 0;

  boolean fullscreen = false;
  boolean auto_scroll = true;


  Activity activity;

  Context context;
  LayoutInflater inflater;

  String tag = "MyDialogFragment";
  String title;
  CharSequence message;

  TextView title_tv;
  ListView listView;

  View contentView;

  int backgroundColor = BACKGROUND_COLOR_LIGHT;

//int dividerColor=0xffbbbbbb;
  int dividerColor=0xffaaaaff;
  int dividerHeight=1;

  int viewLeftMargin = 0;

  int titleTextColor = TITLE_TEXT_COLOR_LIGHT;
  int titleTextSize = TITLE_TEXT_SIZE;
  int messageTextSize = MESSAGE_TEXT_SIZE;

  int buttonTextSize = 17;
  int checkBoxTextSize = 18;
  int radioButtonTextSize = 18;


  ShapeDrawable button_up;
  ShapeDrawable button_down;

  DialogInterface.OnShowListener  onShowListener;

  String button0_text = null;
  Button button0 = null;
  DialogInterface.OnClickListener  onClickListener0;

  String button1_text = null;
  Button button1 = null;
  DialogInterface.OnClickListener  onClickListener1;

  String button2_text = null;
  Button button2 = null;
  DialogInterface.OnClickListener  onClickListener2;

  View.OnClickListener onTitleClickListener;

  int button_count = 0;


  private int title_button_left_img = 0;
  private int title_button_right_img = 0;
  private int title_button_padding = 0;

  private View title_view_right = null;

  private ImageButton title_button_left = null;
  private ImageButton title_button_right = null;


  private DialogInterface.OnClickListener  onClickListenerLeft;
  private DialogInterface.OnClickListener  onClickListenerRight;

  DialogInterface.OnCancelListener onCancelListener;
  DialogInterface.OnDismissListener onDismissListener;

  boolean auto_dismiss = true;


  public boolean onTitleTouch(View v, MotionEvent event) { return false; }
  public void onTitleClick(View v) {}


  int pix(float dp)
  { float dpi = context.getResources().getDisplayMetrics().densityDpi;
    return (int)(0.5 + dp * (dpi/160f));
   }


  public MyDialogFragment() {
     // empty constructor (necessary !)
     activity = null;
     title = null;
     style = def_style;
     context = null;
     inflater = null;
  }


  public MyDialogFragment(Activity act) { 
     activity = act;
     title = null;
     style = def_style;
     context = new ContextThemeWrapper(activity,dialog_styles[style]);
     inflater = 
      (LayoutInflater)context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
  }

  public MyDialogFragment(Activity act, String t) { 
     activity = act;
     title = t;
     style = def_style;
     context = new ContextThemeWrapper(activity,dialog_styles[style]);
     inflater = 
      (LayoutInflater)context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
  }

  public MyDialogFragment(Activity act, int s) { 
     activity = act;
     title = null;
     style = s;
     context = new ContextThemeWrapper(activity,dialog_styles[style]);
     inflater = 
      (LayoutInflater)context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
  }

  public MyDialogFragment(Activity act, String t, int s) { 
     activity = act;
     title = t;
     style = s;
     context = new ContextThemeWrapper(activity,dialog_styles[style]);
     inflater = 
      (LayoutInflater)context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
  }



  public Context getContext() { return context; }

  public Dialog show() { return show(false); }

  public Dialog show_fullscreen() { return show(true); }

  public Dialog show(boolean full) 
  { 
    if (activity.isFinishing()) return null;

    fullscreen = full;

    // do not create default left button if not in fullscreen mode
    if (!full && title_button_left_img == 0) title_button_left_img = -1;

  //FragmentManager fm = activity.getSupportFragmentManager();
  FragmentManager fm = activity.getFragmentManager();

    FragmentTransaction ft = fm.beginTransaction();

    // ensure that no other instance is still visible (really necessary ?)
    Fragment frag = fm.findFragmentByTag(tag);
    if (frag != null) ft.remove(frag);

    //ft.addToBackStack(null);

    ft.add(this,tag);
    ft.commitAllowingStateLoss();

    Dialog diag = getDialog();

    return diag;
   }
 
/*
  public void close()
  { FragmentManager fm = activity.getFragmentManager();
    //FragmentManager fm = activity.getSupportFragmentManager();
    Fragment frag = fm.findFragmentByTag(tag);
    if (frag != null) {
      DialogFragment df = (DialogFragment)frag;
      df.dismiss();
    }
  }
*/

  @Override
  public void dismiss()
  { //if (!isShowing()) return;
    super.dismissAllowingStateLoss();
   }

  public boolean isShowing()
  { 
/*
    FragmentManager fm = activity.getFragmentManager();
    //FragmentManager fm = activity.getSupportFragmentManager();
    Fragment frag = fm.findFragmentByTag(tag);
    return frag != null;
*/
    return getDialog() != null && getDialog().isShowing();
  }


  public ListView newListView() { 
      ListView lv = new ListView(context);
      lv.setDivider(new ColorDrawable(dividerColor));
      lv.setDividerHeight(dividerHeight);
/*
      lv.addFooterView(new View(context));
*/
      return lv;
  }

  public TextView newTextView() { return new TextView(context); }
  public EditText newEditText() { return new EditText(context); }

  public TextView newBoxTextView(int clr) {
    TextView tv = new TextView(context);
    GradientDrawable bg = new GradientDrawable();
    bg.setCornerRadius(0);
    bg.setColor(clr);
    bg.setStroke(pix(1),0xff333333);
    tv.setBackground(bg);
    tv.setTextSize(16);
    return tv;
  }


  public ProgressBar newProgressBar() {
    ProgressBar pb = new ProgressBar(context,null,
                                     android.R.attr.progressBarStyleHorizontal);
/*
    float[] rad = new float[8];
    for(int i=0;i<8;i++) rad[i] = pix(8);
    ShapeDrawable shape = new ShapeDrawable(new RoundRectShape(rad,null,null));
    shape.getPaint().setColor(0xffaa0000);
*/
    GradientDrawable shape =  new GradientDrawable();
    shape.setColor(0xffaa0000);
    shape.setCornerRadius(pix(8));

    pb.setProgressDrawable(new ClipDrawable(shape,Gravity.LEFT,
                                                  ClipDrawable.HORIZONTAL));

    GradientDrawable bg_shape =  new GradientDrawable();
    bg_shape.setColor(0x00000000);
    bg_shape.setCornerRadius(pix(8));
    bg_shape.setStroke(1,0xff000000);

    pb.setBackground(bg_shape);

    return pb;
  }


  public CheckBox newCheckBox() { 
    CheckBox cb = new CheckBox(context);
    setButtonDrawable(cb);
    cb.setTextSize(checkBoxTextSize);
    return cb;
  }

  public SeekBar newSeekBar()   { return new SeekBar(context);  }

  public CheckBox findCheckBox(int id)
  { if (contentView == null) return null;
    CheckBox cb = (CheckBox)contentView.findViewById(id);
    if (cb != null) setButtonDrawable(cb);
    return cb;
   }


  public RadioButton newRadioButton() 
  { RadioButton but = new RadioButton(context);
    but.setTextSize(radioButtonTextSize);
    but.setPadding(pix(0),pix(2),pix(0),pix(7));
    setButtonDrawable(but);
    return but;
  }

  public RadioButton findRadioButton(int id)
  { if (contentView == null) return null;
    RadioButton but = (RadioButton)contentView.findViewById(id);
    if (but != null) setButtonDrawable(but);
    return but;
   }



  public Button newButton(String text) { return newButton(text,false); }

  public Button newButton(String text, final boolean title_but) 
  {
    Button button = new Button(context);
    button.setSingleLine(true);
    button.setText(text);

    if (title_but)
    { button.setPadding(0,0,0,0);
      button.setBackground(null);
      button.setTextSize(1.4f*buttonTextSize);
      button.setTextColor(0xffa0a0a0);
     }
    else
    { button.setTextSize(buttonTextSize);
      if (holo()) button.setBackground(button_up);
      //if (buttonTextBold) button.setTypeface(null,Typeface.BOLD);
     }

    button.setOnTouchListener(new View.OnTouchListener() {
         public boolean onTouch(View v, MotionEvent event) {

             activity.onUserInteraction();

             Button b = (Button)v;
             if (event.getAction() == MotionEvent.ACTION_DOWN)
             { b.setBackground(button_down);
               //b.setTextColor(0xffffffff);
              }

             if (event.getAction() == MotionEvent.ACTION_UP)
             { if (title_but) 
               { b.setTextColor(0xff606060);
                 b.setBackground(null);
                }
               else
                 if (!auto_dismiss)
                 { //b.setTextColor(0xff000000);
                   b.setBackground(button_up);
                  }
              }

             return false;
         }
    });
  
    return button;
  }

  public void setAnimationStyle(int r) { anim_style = r; }

  public void setOnShowListener(DialogInterface.OnShowListener listener) {
     onShowListener = listener;
  }


  public void setNegativeButton(String txt,
                                DialogInterface.OnClickListener listener)
  { button1_text = txt;
    onClickListener1 = listener;
    button_count++;
   }


  public void setPositiveButton(String txt,
                                DialogInterface.OnClickListener listener)
  { button2_text = txt;
    onClickListener2 = listener;
    button_count++;
   }


  public void setNeutralButton(String txt,
                               DialogInterface.OnClickListener listener)
  { button0_text = txt;
    onClickListener0 = listener;
    button_count++;
   }

  public void setOnTitleClickListener(View.OnClickListener listener)
  { onTitleClickListener = listener; }

  public Button getNegativeButton() { return button1; }
  public Button getPositiveButton() { return button2; }
  public Button getNeutralButton() { return button0; }


  public void setTitleButton(int res, DialogInterface.OnClickListener listener)
  { title_button_right_img = res;
    onClickListenerRight = listener;
   }

  public void setTitleViewRight(View view) { title_view_right = view; }
  public View getTitleViewRight() { return title_view_right; }

  public ImageButton getTitleButtonRight() { return title_button_right; }


  public void setTitleButtonLeft(int img_res,
                                    DialogInterface.OnClickListener listener)
  { title_button_left_img = img_res;
    onClickListenerLeft = listener;
   }


  public void setTitleButtonPadding(int p) { title_button_padding = p; }


  public void setOnCancelListener(DialogInterface.OnCancelListener listener) {
    onCancelListener = listener;
  }

  public void setOnDismissListener(DialogInterface.OnDismissListener listener) {
    onDismissListener = listener;
  }


  private void add_buttons(LinearLayout layout) 
  {
     if (button_count == 0) return;

     LinearLayout buttonLine = new LinearLayout(context);
     buttonLine.setOrientation(LinearLayout.HORIZONTAL);

     if (button1_text != null) 
     { button1 = newButton(button1_text);
       button1.setOnClickListener( new View.OnClickListener() {
              public void onClick(View v) {
                  if (onClickListener1 != null) {
                    onClickListener1.onClick(getDialog(),1);
                  }
                  if (auto_dismiss) dismiss();
              }
        });
       LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT,
                                              LayoutParams.WRAP_CONTENT, 1);
       params.leftMargin=-1;
       buttonLine.addView(button1,params);
     }

     if (button0_text != null) 
     {  button0 = newButton(button0_text);
        button0.setOnClickListener( new View.OnClickListener() {
              public void onClick(View v) {
                  if (onClickListener0 != null) {
                    onClickListener0.onClick(getDialog(),0);
                  }
                  if (auto_dismiss) dismiss();
              }
        });
       LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT,
                                              LayoutParams.WRAP_CONTENT, 1);
       params.leftMargin=-1;
       buttonLine.addView(button0,params);
     }

     if (button2_text != null) 
     { button2 = newButton(button2_text);
       button2.setOnClickListener( new View.OnClickListener() {
              public void onClick(View v) {
                  if (onClickListener2 != null) {
                    onClickListener2.onClick(getDialog(),2);
                  }
                  if (auto_dismiss) dismiss();
              }
        });
       LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT,
                                              LayoutParams.WRAP_CONTENT, 1);
       params.leftMargin=-1;
       buttonLine.addView(button2,params);
     }


     LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT,
                                            LayoutParams.WRAP_CONTENT);

     params.topMargin=10;
     params.bottomMargin=0;

     layout.addView(buttonLine,params);
  }




    public void setButtonText(int i, String txt) {
        Button but = null;
        switch(i) {
          case 0: but = button0;
                  break;
          case 1: but = button1;
                  break;
          case 2: but = button2;
                  break;
        }
        if (but != null) but.setText(txt);
    }

    public void setButtonDrawable(CheckBox cb)
    { if (holo()) 
      { int  btn_check_id = context.getResources().getIdentifier("btn_check",
                                                                 "drawable",
                                                                 "android");
        cb.setButtonDrawable(btn_check_id);
       }
    }

    public void setButtonDrawable(RadioButton but)
    { if (holo()) 
      { int  btn_radio_id = context.getResources().getIdentifier("btn_radio",
                                                                 "drawable",
                                                                 "android");
        but.setButtonDrawable(btn_radio_id);
       }
    }
 


    public void   setTag(String s) { tag = s; }

    //public String getTag() { return tag; }

    public void setAutoDismiss(boolean b) { auto_dismiss = b; }
    public void setAutoScroll(boolean b) { auto_scroll = b; }

    public void setBackgroundColor(int clr) { backgroundColor = clr; }

    public void setTitle(String s) { title = s; }

    public void setLeftMargin(int x) { viewLeftMargin = x; }

    public void setTitleTextSize(int sz) { titleTextSize = sz; }
    public void setMessageTextSize(int sz) { messageTextSize = sz; }
    public void setButtonTextSize(int sz) { buttonTextSize = sz; }

    public void setViewPadding(int left, int top, int right, int bottom)
    { if (contentView != null) 
        contentView.setPadding(pix(left),pix(top),pix(right),pix(bottom));
     }

    public void setViewPadding(int dp) { 
      setViewPadding(dp,dp,dp,dp);
    }

    public View setView(View v)
    { LinearLayout ll = new LinearLayout(context);
      ll.setOrientation(LinearLayout.VERTICAL);
      ll.addView(v);
      contentView = ll;
      return v;
     }

    public View setView(int res) { 
      return setView(inflater.inflate(res,null));
     }


    public View addView(View v)
    { if (contentView == null)
        setView(v);
      else
        ((LinearLayout)contentView).addView(v);
      return v;
     }

    public View addView(int res) { 
      return addView(inflater.inflate(res,null));
     }


    public void addSeparator(int clr)
    { View sep = new View(context);
      sep.setBackgroundColor(clr);
      addView(sep);
      sep.getLayoutParams().height = pix(0.5f);
     }


    @Override
    public void onCreate(Bundle savedInstanceState) 
    { 
      super.onCreate(savedInstanceState);
/*
      if (savedInstanceState != null &&
          savedInstanceState.getInt("SavedInstance") == 1) 
      {
        // close immediately in case of recreation from a saved state
        // setRetainInstance(false) should prevent onCreate being called
        // in this case - but this does not work

        dismiss();
        return;
       }
*/

      if (context == null)
      { // created by default constructor 
        dismiss();
        return;
      }


     setStyle(DialogFragment.STYLE_NO_TITLE,dialog_styles[style]);

     if (style == STYLE_HOLO_DARK || style == STYLE_MATERIAL_DARK)
     { backgroundColor = BACKGROUND_COLOR_DARK;
       titleTextColor = TITLE_TEXT_COLOR_DARK;
      }
     else
     { backgroundColor = BACKGROUND_COLOR_LIGHT;
       titleTextColor = TITLE_TEXT_COLOR_LIGHT;
      }
  
/*
     WindowManager wm = 
              (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
     Display display = wm.getDefaultDisplay(); 
*/

     button_up = new ShapeDrawable(new RectShape());

     if (style == STYLE_HOLO_LIGHT)
       button_up.getPaint().setColor(0xff707070);
     else
       button_up.getPaint().setColor(0xff555555);

     button_up.getPaint().setStyle(Paint.Style.STROKE);
     button_up.getPaint().setStrokeWidth(2);


     button_down = new ShapeDrawable(new RectShape());
     button_down.getPaint().setColor(TITLE_TEXT_COLOR_LIGHT);
     button_down.getPaint().setStyle(Paint.Style.FILL);

     // create a unique tag
     
     long msec = System.currentTimeMillis();
     tag = String.format("Diag-%d",msec);

     //setRetainInstance(false);

    }


    @Override
    public void onStop() 
    { super.onStop();
      //dismiss();
     }

    @Override
    public void onStart() 
    { super.onStart();
      Dialog dialog = getDialog();
    //Window win = dialog.getWindow();
    //win.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
    //win.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);

   /*
     if (!fullscreen) 
     { Window win = dialog.getWindow();
       win.clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
       WindowManager.LayoutParams params = win.getAttributes();
       params.width = ViewGroup.LayoutParams.MATCH_PARENT;
       params.height = ViewGroup.LayoutParams.MATCH_PARENT;
       win.setAttributes(params);
     }
   */

   }


    @Override
    public void onResume() {
/*
      Dialog dialog = getDialog();
      Window win = dialog.getWindow();
      if (!fullscreen)  {
         win.setGravity(Gravity.TOP | Gravity.LEFT);
         WindowManager.LayoutParams params = win.getAttributes();
         params.x = 500;
         params.y = 1000;
         win.setAttributes(params);
      }
*/
      super.onResume();
   }


  public void closeKeyboard(View view) {
    //new MyToast(context,"close keyboard",0).show();
    InputMethodManager imm = 
    (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
  }

  public void closeKeyboard() {
    View focus = getDialog().getCurrentFocus();
    if (focus != null) closeKeyboard(focus); 
  }
   

    @Override
    public void onDismiss(DialogInterface dialog) {

      // seems not to work
      Dialog diag = getDialog();
      if (diag != null)
      { View focus = diag.getCurrentFocus();
        if (focus != null) closeKeyboard(focus); 
       }

      if (onDismissListener != null) onDismissListener.onDismiss(dialog);

      super.onDismiss(dialog);
    }

    @Override
    public void onCancel(DialogInterface dialog) {
       super.onCancel(dialog);
       if (onCancelListener != null) onCancelListener.onCancel(dialog);
    }


   public void setMessage(CharSequence msg) { message = msg; }

   public ListView addListView(BaseAdapter adapter,
                               final DialogInterface.OnClickListener listener)
   { 
      listView = newListView();

      listView.setAdapter(adapter);
      listView.setOnItemClickListener(
         new AdapterView.OnItemClickListener() {
           public void onItemClick(AdapterView<?> par,View v, int p, long id) {
               listener.onClick(getDialog(),p);
           }
      });

      addView(listView);

      return listView;
    }

   public TextView getTitleView() { return title_tv; }

   public ListView setItems(CharSequence items[], 
                        final DialogInterface.OnClickListener listener)
   { 
     ArrayAdapter<CharSequence> adapter =
       new ArrayAdapter<CharSequence>(context,
                               android.R.layout.simple_list_item_1, items)
        { @Override
          public View getView(int pos, View view, ViewGroup parent)
          { TextView tv  = (TextView)super.getView(pos,view,parent);
            tv.setTextSize(20);
            int p = pix(6);
            tv.setPadding(2*p,p,p,p);
            if (style == STYLE_TRADITIONAL)
            { tv.setBackgroundColor(0xff000000);
              tv.setTextColor(0xffdddddd);
             }
            else
            if (style == STYLE_HOLO_LIGHT)
              tv.setTextColor(0xff333333);
            else
            if (style == STYLE_MATERIAL_LIGHT)
              tv.setTextColor(0xff555555);
            else
              tv.setTextColor(0xffcccccc);
            return tv;
           }
         };

      return addListView(adapter,listener);
    }



    private View createView()
    { 
      // title

      LinearLayout titleLayout = new LinearLayout(context);

      int dp = pix(1);

      if (title_button_left_img == 0)
        title_button_left_img = global_title_button_left_img;

      if (title_button_left_img > 0)
      { ImageButton b = new ImageButton(context);
        b.setContentDescription("sTracks Logo");
        b.setImageResource(title_button_left_img);
        b.setScaleType(ImageView.ScaleType.FIT_CENTER);
        //b.setScaleType(ImageView.ScaleType.CENTER);
        //b.setScaleType(ImageView.ScaleType.CENTER_CROP);
        b.setBackgroundColor(0x00000000);

        int x = title_button_padding;
        b.setPadding(x,x,x,x);

        b.setOnClickListener( new View.OnClickListener() {
            public void onClick(View v) {
                if (onClickListenerLeft != null)
                  onClickListenerLeft.onClick(null,1);
            }
        });

        LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT,
                                               LayoutParams.MATCH_PARENT);
        params.topMargin=2*dp;
        params.leftMargin=2*dp;
        params.width = 48*dp;
        params.height = 48*dp;
        titleLayout.addView(b,params);

        title_button_left = b;
       }


      if (title != null)
      { title_tv = new TextView(context);
        title_tv.setTextColor(titleTextColor);

        title_tv.setTextSize(titleTextSize);

        if (title_button_left == null)
          title_tv.setPadding(8*dp,0,4*dp,0);
        else
          title_tv.setPadding(6*dp,0,4*dp,3*dp);

        title_tv.setGravity(Gravity.CENTER_VERTICAL);

        title_tv.setText(title);

        title_tv.setOnTouchListener(new View.OnTouchListener() {
             public boolean onTouch(View v, MotionEvent event) { 
                  activity.onUserInteraction();
                  return onTitleTouch(v,event); 
             }
        });


/*
        title_tv.setOnClickListener(new View.OnClickListener() {
             public void onClick(View v) { onTitleClick(view); }
        });
*/
        if (onTitleClickListener != null)
          title_tv.setOnClickListener(onTitleClickListener);

  
        LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT,
                                                 LayoutParams.MATCH_PARENT, 1);
        titleLayout.addView(title_tv,params);
      }

      if (title_button_right_img != 0)
      { ImageButton but = new ImageButton(context);
        but.setContentDescription("Title Button Image");
        but.setImageResource(title_button_right_img);
        but.setScaleType(ImageView.ScaleType.FIT_CENTER);
        but.setBackgroundColor(0x00000000);
        but.setOnClickListener( new View.OnClickListener() {
            public void onClick(View v) {
                if (onClickListenerRight != null)
                  onClickListenerRight.onClick(null,1);
            }
        });
 
        title_button_right = but;

        LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT,
                                                 LayoutParams.MATCH_PARENT);
        params.topMargin=dp;
        params.rightMargin=-8*dp;
        titleLayout.addView(but,params);
      }

      if (title_view_right != null)
      { LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT,
                                               LayoutParams.WRAP_CONTENT);
        params.topMargin=2*dp;
        titleLayout.addView(title_view_right,params);
      }


      LinearLayout layout = new LinearLayout(context);
      layout.setOrientation(LinearLayout.VERTICAL);
      layout.setBackgroundColor(backgroundColor);

      if (title_tv != null)
      { layout.addView(titleLayout);
/*
        titleLayout.getLayoutParams().height = 50*dp;
*/
        titleLayout.setMinimumHeight(52*dp);
       }

      View sep = new View(context);
      if (dark_mode())
        sep.setBackgroundColor(0xff777777);
      else
        sep.setBackgroundColor(titleTextColor);

      layout.addView(sep);
      //sep.getLayoutParams().height = (int)(1.5f*dp);
      sep.getLayoutParams().height = (int)(1.0f*dp);

      // message

      if (message != null)
      { TextView tv = new TextView(context);
        if (dark_mode())
          tv.setTextColor(0xffffffff);
        else
          tv.setTextColor(0xff000000);

        tv.setTextSize(messageTextSize);

        if (contentView == null && button_count == 0)
         tv.setPadding(8*dp,5*dp,8*dp,10*dp);

        else
          tv.setPadding(8*dp,5*dp,8*dp,4*dp);

        tv.setText(message);
  
        LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT,
                                               LayoutParams.WRAP_CONTENT);
        params.bottomMargin = 0;
        layout.addView(tv,params);
      }


      if (contentView != null)
      {
        if (auto_scroll && button_count > 0 && listView == null)
        { ScrollView sv = new ScrollView(context);
          sv.addView(contentView);
          layout.addView(sv);
          LayoutParams params = (LayoutParams)sv.getLayoutParams();
          params.weight = 1;
          if (viewLeftMargin != 0) params.leftMargin = viewLeftMargin;
         }
        else
        { layout.addView(contentView);
          LayoutParams params = (LayoutParams)contentView.getLayoutParams();
          params.weight = 1;
          if (viewLeftMargin != 0) params.leftMargin = viewLeftMargin;
         }
      }

      add_buttons(layout);

      if (fullscreen && Build.VERSION.SDK_INT >= 35)
      { int margin_top = 0;
        int margin_bot = 0;

        Resources res = getResources();

        int resId = res.getIdentifier("status_bar_height","dimen","android");
        if (resId > 0) margin_top = res.getDimensionPixelSize(resId);

        resId = res.getIdentifier("navigation_bar_height","dimen","android");
        if (resId > 0) margin_bot = res.getDimensionPixelSize(resId);

        layout.setPadding(0,margin_top,0,margin_bot);
      }



      return layout;
    }

  
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup parent, 
                                                       Bundle state) 
    {
/*    
      Window win = getDialog().getWindow();
      win.getDecorView().setOnTouchListener(
          new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                     //new MyToast(context,"onTouch",0).show();
                     activity.onUserInteraction();
                     return false;
                }
        });
*/

    // ensure that activity != null
    if (activity == null)  activity = getActivity();

      activity.getWindow().setSoftInputMode(
             WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

      if (fullscreen) 
        return createView();
      else
        return super.onCreateView(inflater, parent, state);
     }
      
      
  @Override
  public void onSaveInstanceState(Bundle state) 
  { // mark state as saved by setting a flag
    state.putInt("SavedInstance", 1);
    super.onSaveInstanceState(state);
   }


  @Override
  public Dialog onCreateDialog(Bundle state) 
  {
    // ensure that context != null
    if (context == null) context = getActivity();

    if (fullscreen) {
     //return super.onCreateDialog(state);
     Dialog dialog = super.onCreateDialog(state);
     dialog.setOnShowListener(onShowListener);
     return dialog;
    }


    AlertDialog.Builder  builder = new AlertDialog.Builder(context);
    builder.setView(createView());
    AlertDialog dialog = builder.create();

    dialog.setOnShowListener(onShowListener);
    dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);

    Window win = dialog.getWindow();
    WindowManager.LayoutParams params = win.getAttributes();
    params.width = ViewGroup.LayoutParams.MATCH_PARENT;

 // params.height = ViewGroup.LayoutParams.MATCH_PARENT;
    params.height = ViewGroup.LayoutParams.WRAP_CONTENT;

    win.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

  //win.setGravity(Gravity.BOTTOM);
    win.setGravity(Gravity.CENTER);

    return dialog;
  }

  @Override
  public void onViewCreated(View view, Bundle args) { 

    super.onViewCreated(view,args);

/*
    Window win = getDialog().getWindow();
    win.getDecorView().setOnTouchListener(
          new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                     activity.onUserInteraction();
                     return false;
                }
        });
*/
    }

  @Override
  public void onActivityCreated(Bundle args) 
  { super.onActivityCreated(args);
    Dialog dialog = getDialog();
    Window win = dialog.getWindow();
    win.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
/*
    win.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
*/
    if (anim_style != 0) 
      win.getAttributes().windowAnimations = anim_style;
    else
      if (fullscreen && def_anim_style != 0) 
        win.getAttributes().windowAnimations = def_anim_style;

   }


   public Window getWindow() { 
     Dialog dialog = getDialog();
     return dialog.getWindow();
   }



// adding Layouts

  private int DipToPixels(float dp)
  { float dpi = context.getResources().getDisplayMetrics().densityDpi;
    return (int)(0.5 + dp * (dpi/160f));
   }

  private String format_value(int val, int min, int precision, String unit, 
                                                               String zero_val)
  { 
    if (val <= min && zero_val != null) return zero_val;

    val *= precision;

    if (unit == null) return "" + val;

    if (unit.equals("mm:ss"))
    { int s = val % 60;
      int m = val / 60;
      return String.format("%d:%02d",m,s);
     }

    return String.format("%d %s",val,unit);
  }

  public SeekBar addSeekBar(final LinearLayout layout, 
                            final String title, 
                            int value, int min_x, int max_x, 
                            final String unit, 
                            final String zero_value,
                            final String description)
  { return addSeekBar(layout,title,value,min_x,max_x,1,unit,zero_value,
                                                            description);
    }



  public SeekBar addSeekBar(final LinearLayout layout, 
                            final String title, 
                            int value, int min_x, int max_x, 
                            final int precision,
                            final String unit, 
                            final String zero_value,
                            final String description)
  {

    final int min = min_x/precision;
    final int max = max_x/precision;

    value = value/precision;

    LinearLayout title_layout = new LinearLayout(context);
    title_layout.setOrientation(LinearLayout.HORIZONTAL);

    TextView title_text = newTextView();
    title_text.setTextSize(19);
    title_text.setText(title);
    title_layout.addView(title_text);
    ((LayoutParams)title_text.getLayoutParams()).width =
                                                     LayoutParams.FILL_PARENT;
    ((LayoutParams)title_text.getLayoutParams()).weight = 1.0f;

    final TextView value_text = newTextView();
    //value_text.setGravity(Gravity.RIGHT);
    value_text.setGravity(Gravity.LEFT);
    value_text.setTypeface(null,Typeface.BOLD);
    value_text.setTextSize(18);
    value_text.setSingleLine(true);

    value_text.setText(format_value(value,min,precision,unit,zero_value));

    title_layout.addView(value_text);
    ((LayoutParams)value_text.getLayoutParams()).width = DipToPixels(60);

    layout.addView(title_layout);
    LayoutParams params = (LayoutParams)title_layout.getLayoutParams();
  //params.topMargin = DipToPixels(15);
    params.topMargin = DipToPixels(10);
    params.rightMargin = DipToPixels(5);



    SeekBar seek_bar = newSeekBar();

    seek_bar.setMax(max - min);
    seek_bar.setProgress(value-min);

    seek_bar.setOnSeekBarChangeListener(
         new SeekBar.OnSeekBarChangeListener() {
         @Override
         public void onStopTrackingTouch(SeekBar arg0) {}

         @Override
         public void onStartTrackingTouch(SeekBar arg0) {}

         @Override
         public void onProgressChanged(SeekBar sb, int x, boolean arg){
             int val = x + min;
             value_text.setText(format_value(val,min,precision,unit,zero_value));
         }
        });


    layout.addView(seek_bar);
    ((LayoutParams)seek_bar.getLayoutParams()).topMargin = DipToPixels(5);

    if (description != null)
    { TextView description_text = newTextView();
      description_text.setTextSize(15);
      description_text.setText(description);
      layout.addView(description_text);
      ((LayoutParams)description_text.getLayoutParams()).leftMargin = 
                                                           DipToPixels(25);
      ((LayoutParams)description_text.getLayoutParams()).topMargin = 
                                                           DipToPixels(-5);
      ((LayoutParams)description_text.getLayoutParams()).bottomMargin = 
                                                           DipToPixels(2);
     }

    return seek_bar;
  }


}
