/*
 *    Copyright 2020 Google LLC
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *    https://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.google.androidbrowserhelper.demos.customtabsheaders;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.browser.customtabs.CustomTabsCallback;
import androidx.browser.customtabs.CustomTabsClient;
import androidx.browser.customtabs.CustomTabsIntent;
import androidx.browser.customtabs.CustomTabsService;
import androidx.browser.customtabs.CustomTabsServiceConnection;
import androidx.browser.customtabs.CustomTabsSession;

import android.content.ComponentName;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Browser;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    private static final Uri URL = Uri.parse("https://padr31.github.io/");

    private CustomTabsSession mSession;
    private CustomTabsServiceConnection mConnection;

    private boolean connectionValidated = false;

    @Override
    protected void onStart() {
        super.onStart();

        // Set up a callback that launches the cross origin intent after session validated.
        CustomTabsCallback callback = new CustomTabsCallback() {
            @Override
            public void onRelationshipValidationResult(int relation,
                                                       @NonNull Uri requestedOrigin,
                                                       boolean result,
                                                       @Nullable Bundle extras) {
                // Can launch custom tabs intent after session was validated as the same origin.
                connectionValidated = true;
            }
        };

        // Set up a connection that warms up and validates a session.
        mConnection = new CustomTabsServiceConnection() {
            @Override
            public void onCustomTabsServiceConnected(@NonNull ComponentName name,
                                                     @NonNull CustomTabsClient client) {
                // Create session after service connected.
                mSession = client.newSession(callback);
                client.warmup(0);
                // Validate the session as the same origin to allow cross origin headers.
                mSession.validateRelationship(CustomTabsService.RELATION_USE_AS_ORIGIN,
                        URL, null);
            }

            @Override
            public void onServiceDisconnected(ComponentName componentName) {
            }
        };

        String packageName = CustomTabsClient.getPackageName(MainActivity.this, null);
        if (packageName == null) {
            Toast.makeText(getApplicationContext(), "Package name is null.", Toast.LENGTH_SHORT)
                .show();
        } else {
            // Bind the custom tabs service connection.
            CustomTabsClient.bindCustomTabsService(this, packageName, mConnection);
        }

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        findViewById(R.id.btn_extra).setOnClickListener(view -> {
            if (connectionValidated) {
                CustomTabsIntent intent = constructExtraHeadersIntent(mSession);
                intent.launchUrl(MainActivity.this, URL);
            }
        });
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mConnection == null) return;
        this.unbindService(mConnection);
        mConnection = null;
        connectionValidated = false;
    }

    private CustomTabsIntent constructExtraHeadersIntent(CustomTabsSession session) {
        CustomTabsIntent intent = new CustomTabsIntent.Builder(session).build();

        // Example non-cors-whitelisted headers.
        Bundle headers = new Bundle();
        headers.putString("bearer-token", "Some token");
        headers.putString("redirect-url", "Some redirect url");
        intent.intent.putExtra(Browser.EXTRA_HEADERS, headers);

        return intent;
    }
}


@@ -1290,16 +1290,46 @@
 rowser;%0A
+import android.widget.Button;%0A
 import a
@@ -1578,58 +1578,8 @@
 n;%0A%0A
-    private boolean connectionValidated = false;%0A%0A
     
@@ -1692,29 +1692,16 @@
 hes the 
-cross origin 
 intent a
@@ -1713,16 +1713,20 @@
 session 
+was 
 validate
@@ -1887,219 +1887,74 @@
 ion,
-%0A                                                       @NonNull Uri requestedOrigin,%0A                                                       boolean result,%0A                                                      
+ @NonNull Uri requestedOrigin,%0A                    boolean result,
  @Nu
@@ -2094,34 +2094,53 @@
     
-connectionValidated = 
+findViewById(R.id.btn_extra).setEnabled(
 true
+)
 ;%0A  
@@ -2399,41 +2399,8 @@
 me,%0A
-                                 
     
@@ -3540,24 +3540,42 @@
 n);%0A%0A       
+ Button btnExtra =
  findViewByI
@@ -3595,81 +3595,92 @@
 tra)
-.setOnClickListener(view -%3E %7B%0A            if (connectionValidated) %7B%0A    
+;%0A        btnExtra.setEnabled(false);%0A        btnExtra.setOnClickListener(view -%3E %7B%0A
     
@@ -3760,28 +3760,24 @@
             
-    
 intent.launc
@@ -3806,30 +3806,16 @@
 , URL);%0A
-            %7D%0A
         
@@ -3946,13 +3946,8 @@
     
-this.
 unbi
@@ -4010,35 +4010,54 @@
     
-connectionValidated = 
+findViewById(R.id.btn_extra).setEnabled(
 false
+)
 ;%0A  

Resolve comments