package com.nielsen.simplestandardandroid8200.activities;

import android.annotation.TargetApi;
import android.os.Bundle;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.nielsen.app.sdk.IAppNotifier;
import com.nielsen.simplestandardandroid8200.R;
import com.nielsen.simplestandardandroid8200.utils.Constants;


/**
 * Created by abdul on 06/02/18.
 */

public class OptOutActivity extends AppCompatActivity implements IAppNotifier {

    WebView webView;
    LandingActivity la = new LandingActivity();
    String optOutUrl = "";

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_optout);

        optOutUrl = getIntent().getStringExtra(Constants.INTENT_OPTOUT_URL);

        webView = (WebView) findViewById(R.id.webView);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setWebViewClient(new WebViewClient() {

            @SuppressWarnings("deprecation")
            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                Toast.makeText(OptOutActivity.this, description, Toast.LENGTH_SHORT).show();
            }
            @TargetApi(android.os.Build.VERSION_CODES.M)
            @Override
            public void onReceivedError(WebView view, WebResourceRequest req, WebResourceError rerr) {
                // Redirect to deprecated method, so you can use it in all SDK versions
                onReceivedError(view, rerr.getErrorCode(), rerr.getDescription().toString(), req.getUrl().toString());
            }
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {

                //We are tracking the OptOut url selected by the user from optout page.
                //Updating the SDK with the same OptOut status.
                if (url.contains("nielsen")) {
                    la.appSdk.userOptOut(url);
                    if(url.equals("nielsenappsdk://1")){
                        la.isOptIn = false;
                    }else{
                        la.isOptIn = true;
                    }
                }

                return true;
            }
        });

        webView.loadUrl(optOutUrl);
    }

    @Override
    public void onAppSdkEvent(long l, int i, String s) {

    }
}
