@{
    ViewData["Title"] = "Real Estate Downloader";
}

<h2>Real Estate Website Downloader</h2>

<div ng-app="realEstateApp" ng-controller="RealEstateController">
    <form ng-submit="fetchImages()">
        <label for="urlInput">Enter Website URL:</label>
        <input type="text" id="urlInput" ng-model="websiteUrl" placeholder="https://example.com" required />
        <button type="submit">Fetch Images</button>
    </form>

    <div ng-if="fetchStatus">
        <p>{{ fetchStatus }}</p>
    </div>

    <!-- Display fetched images before download -->
    <div ng-if="images.length > 0">
        <h3>Fetched Images:</h3>
        <div class="image-container">
            <div ng-repeat="imgSrc in images" class="image-preview">
                <img ng-src="{{ imgSrc }}" alt="Preview Image" />
                <p>{{ imgSrc }}</p>
                <button ng-click="downloadImage(imgSrc)">Download</button>
            </div>
        </div>
    </div>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<script>
    angular.module('realEstateApp', [])
        .controller('RealEstateController', function ($scope, $http) {
            $scope.websiteUrl = '';
            $scope.fetchStatus = '';
            $scope.images = [];

            // Fetch images from the backend
            $scope.fetchImages = function () {
                if ($scope.websiteUrl) {
                    $http.post('/api/realestate/download', { url: $scope.websiteUrl })
                        .then(function (response) {
                            $scope.fetchStatus = 'Images fetched successfully!';
                            $scope.images = response.data.images; // Display the fetched images
                        })
                        .catch(function (error) {
                            $scope.fetchStatus = 'Error fetching images.';
                            console.error(error);
                        });
                }
            };

            // Function to download the image when clicked
            $scope.downloadImage = function (imgSrc) {
                var link = document.createElement('a');
                link.href = imgSrc;
                link.download = imgSrc.split('/').pop(); // Extract filename from URL
                link.click();
            };
        });
</script>

<style>
    .image-container {
        display: flex;
        flex-wrap: wrap;
        margin-top: 20px;
    }

    .image-preview {
        margin: 10px;
        text-align: center;
    }

    .image-preview img {
        width: 150px;
        height: 150px;
        object-fit: cover;
        border: 1px solid #ccc;
        margin-bottom: 10px;
    }

    .image-preview button {
        background-color: #4CAF50;
        color: white;
        border: none;
        padding: 5px 10px;
        cursor: pointer;
    }

    .image-preview button:hover {
        background-color: #45a049;
    }
</style>
