package com.unit.websdk;

import android.app.Activity;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.webkit.WebView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.unit.R;


public class WebviewActivity extends Activity {
    private AdWebView adWebView;
    private String url;

    public WebviewActivity() {
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.activity_webview);
        url = getIntent().getStringExtra("url");
        if (TextUtils.isEmpty(url)) {
            Toast.makeText(this, "Ad Url invalid", Toast.LENGTH_LONG).show();
            finish();
            return;
        }
        adWebView = WebViewCache.get(url);
        if (adWebView == null) {
            adWebView = WebViewCache.create(this, url);
            adWebView.loadUrl(url);
        }
        initView(adWebView);
        LigthWebview.add(url, this);
    }

    @Override
    public void onBackPressed() {
        if (adWebView != null && adWebView.canGoBack()) {
            adWebView.goBack();
            return;
        }
        super.onBackPressed();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LigthWebview.remove(url);
        if (adWebView != null) {
            ViewParent viewParent = adWebView.getParent();
            if (viewParent instanceof ViewGroup) {
                ((ViewGroup) viewParent).removeView(adWebView);
            }
            //如果是预加载的页面
            if(!adWebView.isPreload()){
                WebViewCache.close(url);
            }
        }
        adWebView = null;
    }

    private void initView(WebView webview) {
        LinearLayout container = this.findViewById(R.id.webview);
        container.addView(webview, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        GradientDrawable gradientDrawable = new GradientDrawable();
        gradientDrawable.setCornerRadius((float) R.dimen.close_view_corner_radius);
        gradientDrawable.setColor(0x99000000);
    }
}
