/*
 * @Copyright 2018-2026 HardBackNutter
 * @License GNU General Public License
 *
 * This file is part of NeverTooManyBooks.
 *
 * NeverTooManyBooks is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * NeverTooManyBooks is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with NeverTooManyBooks. If not, see <http://www.gnu.org/licenses/>.
 */
package com.hardbacknutter.nevertoomanybooks.sync.calibre;

import android.Manifest;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.Keep;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.MenuProvider;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;

import com.hardbacknutter.nevertoomanybooks.BaseFragment;
import com.hardbacknutter.nevertoomanybooks.R;
import com.hardbacknutter.nevertoomanybooks.activityresultcontracts.PermissionRequester;
import com.hardbacknutter.nevertoomanybooks.databinding.FragmentSyncCalibreBinding;
import com.hardbacknutter.nevertoomanybooks.sync.SyncReaderFragment;
import com.hardbacknutter.nevertoomanybooks.sync.SyncServer;
import com.hardbacknutter.nevertoomanybooks.sync.SyncWriterFragment;
import com.hardbacknutter.util.insets.InsetsListenerBuilder;

/**
 * Starting point for sending and importing books with Calibre.
 * <p>
 * The user can specify the usual import/export options for new and/or updated books.
 * We do not yet support updating single books, nor a list of book ids.
 * <p>
 * The sync-date is set on the <strong>Library</strong> and NOT on individual books.
 */
@Keep
public class CalibreSyncFragment
        extends BaseFragment {

    /** View Binding. */
    private FragmentSyncCalibreBinding vb;

    private PermissionRequester permissionRequester;

    @Override
    public void onCreate(@Nullable final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.CINNAMON_BUN) {
            //noinspection DataFlowIssue
            permissionRequester = new PermissionRequester(getActivity(), this);
            final String calibre = getString(R.string.site_calibre);
            permissionRequester.addPermission(
                    Manifest.permission.ACCESS_LOCAL_NETWORK, true,
                    getString(R.string.warning_local_network_permission_required, calibre),
                    getString(R.string.warning_local_network_permission_denied, calibre)
            );
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull final LayoutInflater inflater,
                             @Nullable final ViewGroup container,
                             @Nullable final Bundle savedInstanceState) {
        vb = FragmentSyncCalibreBinding.inflate(inflater, container, false);
        return vb.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull final View view,
                              @Nullable final Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        InsetsListenerBuilder.fragmentRootView(view);

        final Toolbar toolbar = getToolbar();
        toolbar.setTitle(R.string.action_synchronize);
        toolbar.addMenuProvider(new ToolbarMenuProvider(), getViewLifecycleOwner());

        // Make sure it's GONE, when returning from import/export to this screen
        getFab().setVisibility(View.GONE);

        vb.btnLibMap.setOnClickListener(v -> {
            if (CalibreContentServer.getHostUrl().isEmpty()) {
                openSettings();
            } else {
                onClick(() -> replaceFragment(CalibreLibraryMappingFragment.create(),
                                              CalibreLibraryMappingFragment.TAG));
            }
        });
        vb.btnImport.setOnClickListener(v -> {
            if (CalibreContentServer.getHostUrl().isEmpty()) {
                openSettings();
            } else {
                onClick(() -> replaceFragment(SyncReaderFragment.create(SyncServer.CalibreCS),
                                              SyncReaderFragment.TAG));
            }
        });
        vb.btnExport.setOnClickListener(v -> {
            if (CalibreContentServer.getHostUrl().isEmpty()) {
                openSettings();
            } else {
                onClick(() -> replaceFragment(SyncWriterFragment.create(SyncServer.CalibreCS),
                                              SyncWriterFragment.TAG));
            }
        });
    }

    private void onClick(@NonNull final Runnable action) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.CINNAMON_BUN) {
            permissionRequester.request(Manifest.permission.ACCESS_LOCAL_NETWORK, isGranted -> {
                if (isGranted) {
                    action.run();
                }
            });
        } else {
            action.run();
        }
    }

    private void openSettings() {
        replaceFragment(new CalibrePreferencesFragment(), CalibrePreferencesFragment.TAG);
    }

    private void replaceFragment(@NonNull final Fragment fragment,
                                 @NonNull final String tag) {
        final FragmentManager fm = getParentFragmentManager();
        fm.beginTransaction()
          .setReorderingAllowed(true)
          .addToBackStack(tag)
          .replace(R.id.content_frame, fragment, tag)
          .commit();
    }

    private final class ToolbarMenuProvider
            implements MenuProvider {

        @Override
        public void onCreateMenu(@NonNull final Menu menu,
                                 @NonNull final MenuInflater menuInflater) {
            menu.add(Menu.NONE, R.id.MENU_CALIBRE_SETTINGS, 0, R.string.lbl_settings)
                .setIcon(R.drawable.settings_24px)
                .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
        }

        @Override
        public boolean onMenuItemSelected(@NonNull final MenuItem menuItem) {
            if (menuItem.getItemId() == R.id.MENU_CALIBRE_SETTINGS) {
                openSettings();
                return true;
            }
            return false;
        }
    }
}
