package com.nielsen.simple_noads_android_8100.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.AppSdk;
import com.nielsen.app.sdk.IAppNotifier;
import com.nielsen.app.sdk.NielsenAppSDKJSHandler;
import com.nielsen.simple_noads_android_8100.R;
import com.nielsen.simple_noads_android_8100.models.NielsenInit;
import com.nielsen.simple_noads_android_8100.utils.Constants;

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

public class OptOutActivity extends AppCompatActivity implements IAppNotifier {

    WebView webView;
    LandingActivity la = new LandingActivity();

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_optout);
        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;
            }
        });

        String url = la.appSdk.userOptOutURLString();
        webView.loadUrl(url);
    }

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

    }
}
