/*
 * Copyright (C) 2025 The Android Open Source Project
 *
 * 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
 *
 *      http://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.android.libraries.mobiledatadownload.testing;

import android.net.Uri;

import com.google.android.libraries.mobiledatadownload.downloader.DownloadConstraints;
import com.google.android.libraries.mobiledatadownload.downloader.DownloadRequest;
import com.google.android.libraries.mobiledatadownload.downloader.FileDownloader;
import com.google.android.libraries.mobiledatadownload.internal.logging.LogUtil;
import com.google.android.libraries.mobiledatadownload.file.SynchronousFileStorage;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;

/**
 * A {@link FileDownloader} that "downloads" by copying the file from the application's assets.
 *
 * <p>The filename is the Last Path Segment of the provided `urlToDownload`. For example, the URL
 * https://www.gstatic.com/icing/idd/sample_group/step1.txt will be mapped to the asset named
 * "step1.txt".
 *
 * <p>Note that TestFileDownloader ignores the DownloadConditions.
 */
public final class TestFileDownloader implements FileDownloader {

    private static final String TAG = "TestDataFileDownloader";

    private final FileDownloader delegateDownloader;

    public TestFileDownloader(
            SynchronousFileStorage fileStorage, ListeningExecutorService executor) {
        this.delegateDownloader = new LocalFileDownloader(fileStorage, executor);
    }

    @Override
    public ListenableFuture<Void> startDownloading(DownloadRequest downloadRequest) {
        LogUtil.d(
                "%s: startDownloading; urlToDownload: %s; uriToDownload: %s;",
                TAG, downloadRequest.urlToDownload(), downloadRequest.fileUri());

        Uri fileUri = downloadRequest.fileUri();
        String urlToDownload = downloadRequest.urlToDownload();
        Uri uriToDownload = Uri.parse(urlToDownload);
        DownloadConstraints downloadConstraints = downloadRequest.downloadConstraints();

        return delegateDownloader.startDownloading(
                DownloadRequest.newBuilder()
                        .setFileUri(fileUri)
                        .setUrlToDownload(uriToDownload.getLastPathSegment())
                        .setDownloadConstraints(downloadConstraints)
                        .build());
    }
}
