/*
 * SPDX-FileCopyrightText: 2022 microG Project Team
 * SPDX-License-Identifier: Apache-2.0
 * Notice: Portions of this file are reproduced from work created and shared by Google and used
 *         according to terms described in the Creative Commons 4.0 Attribution License.
 *         See https://developers.google.com/readme/policies for details.
 */

package com.google.android.gms.oss.licenses;

import android.content.res.Resources;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.widget.ScrollView;
import android.widget.TextView;

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

import com.google.android.gms.tasks.Task;
import com.google.android.gms.tasks.Tasks;

import org.microg.gms.common.PublicApi;
import org.microg.gms.oss.licenses.LicenseUtil;

/**
 * An Activity used to display the actual content of a license in res/raw/third_party_licenses generated by oss
 * licenses gradle plugin. This activity is invoked by list items from {@link OssLicensesMenuActivity}.
 */
@PublicApi
public class OssLicensesActivity extends AppCompatActivity {
    private static final String SCROLL_POSITION_EXTRA = "scroll_pos";
    private License license;
    private TextView textView;
    private ScrollView scrollView;
    private int restoredScrollPosition;
    private boolean destroyed;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        destroyed = false;
        license = getIntent().getParcelableExtra("license");
        if (getSupportActionBar() != null) {
            getSupportActionBar().setTitle(this.license.toString());
            getSupportActionBar().setDisplayShowHomeEnabled(true);
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setLogo(null);
        }
        OssLicensesServiceImpl service = new OssLicensesServiceImpl(this);
        Task<String> licenseDetailTask = service.getLicenseDetail(license);
        Task<String> licenseLayoutPackageTask = service.getLicenseLayoutPackage(getPackageName());
        Tasks.whenAll(licenseDetailTask, licenseLayoutPackageTask).addOnCompleteListener((nil) -> {
            if (destroyed || isFinishing()) return;

            // Layout
            String layoutPackage = getPackageName();
            if (licenseLayoutPackageTask.isSuccessful()) {
                layoutPackage = licenseLayoutPackageTask.getResult();
            }
            Resources resources;
            try {
                resources = getPackageManager().getResourcesForApplication(layoutPackage);
            } catch (Exception e) {
                layoutPackage = getPackageName();
                resources = getResources();
            }
            setContentView(getLayoutInflater().inflate(resources.getXml(resources.getIdentifier("libraries_social_licenses_license_activity", "layout", layoutPackage)), null, false));
            textView = findViewById(resources.getIdentifier("license_activity_textview", "id", layoutPackage));
            scrollView = findViewById(resources.getIdentifier("license_activity_scrollview", "id", layoutPackage));

            // Text
            String licenseText = null;
            if (licenseDetailTask.isSuccessful()) {
                licenseText = licenseDetailTask.getResult();
            }
            if (licenseText == null) {
                try {
                    licenseText = LicenseUtil.getLicenseText(this, license);
                } catch (Exception e) {
                    // Ignore
                }
            }
            if (licenseText == null) {
                textView.setText(R.string.license_content_error);
            } else {
                textView.setText(licenseText);
            }

            // Restore scroll position
            if (restoredScrollPosition != 0) {
                scrollView.post(() -> scrollView.scrollTo(0, textView.getLayout().getLineTop(textView.getLayout().getLineForOffset(restoredScrollPosition))));
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        destroyed = true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onRestoreInstanceState(@NonNull Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        restoredScrollPosition = savedInstanceState.getInt(SCROLL_POSITION_EXTRA);
    }

    @Override
    protected void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        if (textView != null && scrollView != null) {
            outState.putInt(SCROLL_POSITION_EXTRA, textView.getLayout().getLineStart(textView.getLayout().getLineForVertical(scrollView.getScrollY())));
        }
    }
}
