/*
 *     Created by Angel Leon (@gubatron), Alden Torres (aldenml)
 *     Copyright (c) 2011-2026, FrostWire(R). All rights reserved.
 * 
 *     This program 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.
 * 
 *     This program 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 this program.  If not, see <https://www.gnu.org/licenses/>.
 */

package org.team_hermes.wireshare.android.util;

import org.team_hermes.wireshare.android.core.ConfigurationManager;
import org.team_hermes.wireshare.android.core.Constants;
import org.team_hermes.wireshare.android.core.FWFileDescriptor;
import org.team_hermes.wireshare.android.gui.NetworkManager;
import org.team_hermes.wireshare.android.gui.transfers.TransferManager;
import org.team_hermes.wireshare.bittorrent.BTEngine;
import com.frostwire.jlibtorrent.Entry;
import com.frostwire.jlibtorrent.TorrentInfo;
import com.frostwire.jlibtorrent.swig.create_torrent;
import com.frostwire.jlibtorrent.swig.error_code;
import com.frostwire.jlibtorrent.swig.file_storage;
import com.frostwire.jlibtorrent.swig.libtorrent;
import com.frostwire.jlibtorrent.swig.set_piece_hashes_listener;
import org.team_hermes.wireshare.util.Logger;
import org.team_hermes.wireshare.util.MimeDetector;

import org.apache.commons.io.FilenameUtils;

import java.io.File;
import java.util.Objects;

/**
 * Utility class for torrent creation and seeding operations
 * 
 * @author copilot
 */
public final class TorrentUtils {
    
    private static final Logger LOG = Logger.getLogger(TorrentUtils.class);

    private TorrentUtils() {
        // Utility class
    }

    /**
     * Seeds a finished HTTP download if seeding is enabled in settings and network conditions allow it.
     * This method handles the configuration checks on the appropriate thread to avoid strict mode violations.
     * 
     * @param savePath The path to the downloaded file
     * @param displayName The display name for the download
     * @param fileType The type of file (e.g., Constants.FILE_TYPE_AUDIO, Constants.FILE_TYPE_DOCUMENTS)
     * @param manager The TransferManager instance
     */
    public static void seedFinishedHttpDownloadIfEnabled(File savePath, String displayName, byte fileType, TransferManager manager) {
        // Move configuration checks to CONFIG_MANAGER thread to avoid strict mode violations
        SystemUtils.postToHandler(SystemUtils.HandlerThreadName.CONFIG_MANAGER, () -> {
            ConfigurationManager cm = ConfigurationManager.instance();
            
            // Only proceed if seeding is enabled
            if (!cm.isSeedFinishedTorrents()) {
                return;
            }
            
            // Check WiFi-only restriction
            if (cm.isSeedingEnabledOnlyForWifi() && !NetworkManager.instance().isDataWIFIUp()) {
                return;
            }
            
            // Don't seed if mobile data savings are on
            if (manager.isMobileAndDataSavingsOn()) {
                return;
            }
            
            // Create FWFileDescriptor for the downloaded file
            if (savePath != null && savePath.exists()) {
                FWFileDescriptor fd = createFileDescriptor(savePath, displayName, fileType);
                if (fd != null) {
                    // Use background thread to create torrent and seed it
                    SystemUtils.postToHandler(SystemUtils.HandlerThreadName.MISC, () -> buildTorrentAndSeedIt(fd, manager));
                }
            }
        });
    }
    
    /**
     * Creates a FWFileDescriptor for the given file
     */
    private static FWFileDescriptor createFileDescriptor(File file, String displayName, byte fileType) {
        if (!file.exists()) {
            return null;
        }
        
        FWFileDescriptor fd = new FWFileDescriptor();
        fd.filePath = file.getAbsolutePath();
        fd.fileSize = file.length();
        fd.dateModified = file.lastModified();
        fd.dateAdded = System.currentTimeMillis();
        fd.mime = MimeDetector.getMimeType(FilenameUtils.getExtension(file.getName()));
        fd.fileType = fileType;
        fd.title = displayName;
        fd.deletable = true;
        
        return fd;
    }
    
    /**
     * Creates a torrent from the file and starts seeding it
     */
    private static void buildTorrentAndSeedIt(final FWFileDescriptor fd, TransferManager manager) {
        try {
            File file = new File(fd.filePath);
            File saveDir = file.getParentFile();
            file_storage fs = new file_storage();
            libtorrent.add_files(fs, file.getAbsolutePath());
            fs.set_name(file.getName());
            create_torrent ct = new create_torrent(fs);
            ct.set_creator("WireShare " + Constants.FROSTWIRE_VERSION_STRING + " build " + Constants.FROSTWIRE_BUILD);
            ct.set_priv(false);
            final error_code ec = new error_code();
            libtorrent.set_piece_hashes_ex(ct, Objects.requireNonNull(saveDir).getAbsolutePath(), new set_piece_hashes_listener(), ec);
            final byte[] torrent_bytes = new Entry(ct.generate()).bencode();
            final TorrentInfo tinfo = TorrentInfo.bdecode(torrent_bytes);
            // Create the TorrentHandle object and add it to the libtorrent session
            BTEngine.getInstance().download(tinfo, saveDir, new boolean[]{true}, null, manager.isDeleteStartedTorrentEnabled());
            LOG.info("Successfully created and started seeding torrent for HTTP download: " + fd.filePath);
        } catch (Throwable e) {
            LOG.error("Error creating torrent for HTTP download seed: " + fd.filePath, e);
        }
    }
}