package com.ydl.webview;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.drawable.ClipDrawable;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.LayerDrawable;
import androidx.core.content.ContextCompat;
import android.util.AttributeSet;
import android.view.Gravity;
import android.widget.ProgressBar;

import com.tencent.smtt.sdk.WebView;

/**
 * Created by jinkai on 16/5/9.
 */
public class ProgressWebView extends WebView {
    protected ProgressBar progressbar;

    protected String Title;

    public ProgressWebView(Context context, AttributeSet attrs) {
        super(context, attrs);
        try {
            progressbar = new ProgressBar(context, null, android.R.attr.progressBarStyleHorizontal);
            progressbar.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, 5));
            progressbar.setProgressDrawable(getResources().getDrawable(R.drawable.platform_web_progressbar));
            LayerDrawable drawable = (LayerDrawable) progressbar.getProgressDrawable();
            GradientDrawable gradientDrawable = new GradientDrawable();
            gradientDrawable.setColor(ContextCompat.getColor(context,com.ydl.ydlcommon.R.color.platform_main_theme));
            ClipDrawable clipDrawable = new ClipDrawable(gradientDrawable, Gravity.START, ClipDrawable.HORIZONTAL);
            drawable.setDrawableByLayerId(android.R.id.progress, clipDrawable);
            drawable.setDrawableByLayerId(android.R.id.secondaryProgress, clipDrawable);


            addView(progressbar);
            setProgressbar(progressbar);
            setWebChromeClient(new WebChromeClient());
        } catch (Resources.NotFoundException e) {
            e.printStackTrace();
        }
    }

    public class WebChromeClient extends com.tencent.smtt.sdk.WebChromeClient {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (newProgress == 100) {
                progressbar.setVisibility(GONE);
            } else {
                if (progressbar.getVisibility() == GONE)
                    progressbar.setVisibility(VISIBLE);
                progressbar.setProgress(newProgress);
            }
            super.onProgressChanged(view, newProgress);
        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            Title = title;
        }


    }

    public String getTitle() {
        return Title;
    }

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

    public ProgressBar getProgressbar() {
        return progressbar;
    }

    public void setProgressbar(ProgressBar progressbar) {
        this.progressbar = progressbar;
    }
}