package com.bernard.mcqinator.inutil.android;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.bernard.mcqinator.R;

import java.util.Stack;

/**
 * @author samy
 * @date on 04/08/17.
 */

public class WaitingDialog extends Dialog {

    public WaitingDialog(@NonNull Context context) {
        super(context);
    }
    LinearLayout ll;
    Stack<ViewGroup> barsLayout;
    ViewGroup parent;
    LayoutInflater inflater;
    Activity a;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.waitdialog_layout);
        this.inflater = getLayoutInflater();
        ll = findViewById(R.id.waitList);

        barsLayout = new Stack<>();
    }

    private Activity ownerActivity(){
        Activity oA = getOwnerActivity();
        if(oA == null)
            throw new IllegalStateException("The owner's activity is null ... and it should not");
        return oA;
    }

    public int newBar(){
        ownerActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ViewGroup barLayout = (ViewGroup)inflater.inflate(R.layout.waitdialog_progressbar,ll,true);
                barsLayout.push(barLayout);

            }
        });
        return barsLayout.size() + 1;
    }

    public int newBar(int max){
        newBar();
        setMax(max);
        return barsLayout.size();
    }

    private ProgressBar getProgressBar(){
        return ((ProgressBar)barsLayout.peek().findViewById(R.id.progressBar));
    }

    private TextView getProgressText(){
        return ((TextView)barsLayout.peek().findViewById(R.id.progressText));
    }

    public void setMax(final int max){
        ownerActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ProgressBar bar = getProgressBar();
                bar.setMax(max);
                getProgressText().setText(bar.getProgress() + "/" + bar.getMax());
            }
        });

    }

    public void setValue(final int value){
        ownerActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ProgressBar bar = getProgressBar();
                bar.setProgress(value);
                getProgressText().setText(bar.getProgress() + "/" + bar.getMax());
            }
        });
    }

    public int removeBar(){
        ownerActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ll.removeView(barsLayout.pop());
            }
        });

        return barsLayout.size() - 1;
    }
}