package com.example.PhotoGallery.Controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.example.PhotoGallery.Components.ImageIngestionCoordinator;
import com.example.PhotoGallery.Models.Photo;
import com.example.PhotoGallery.Services.PhotoService;

@Controller
public class PhotoHomeController {

    @Autowired
    PhotoService photoService;
    @Autowired
    ImageIngestionCoordinator ingestionCoordinator;

    private final int RANDOM_NUMBER_IMAGES = 5;
    private final int FIRST_PAGE = 0;
    private final int PAGE_SIZE = 10;
    private int pageCounter = 0;

    @GetMapping("/")
    public String redirectToHome() {
        return "redirect:/home";
    }

    @GetMapping("/home")
    private String home(Model model) {

        // reset the page counter when the page home page is reloaded
        pageCounter = 0;

        // upon a page refresh we will scan the image directory,
        // if there are any images that are not in the DB we can then compress and
        // insert them

        model.addAttribute("images", photoService.getPagedPhotos(FIRST_PAGE, PAGE_SIZE));
        model.addAttribute("carouselImages", photoService.getRandomPhotos(RANDOM_NUMBER_IMAGES));

        return "home";

    }

    @PostMapping("/scanLibrary")
    @ResponseBody
    public ResponseEntity<Void> scanLibrary() {
        ingestionCoordinator.startIfNotRunning(
                photoService::writeImagesFromDirToDB);
        return ResponseEntity.noContent().build();
    }

    @GetMapping("/loadMoreImages")
    public String loadMoreImages(Model model) {
        int totalPages = photoService.getPagedPhotos(FIRST_PAGE, PAGE_SIZE).getTotalPages();

        // dont load any more images if we have reached the last images
        if (pageCounter == totalPages) {
            return "home :: images";
        }

        pageCounter++;
        model.addAttribute("images", photoService.getPagedPhotos(pageCounter, 30));
        return "home :: images";
    }

    @PostMapping("/search")
    public String search(Model model, @RequestParam("search") String search) {

        List<Photo> searchedPhotos = photoService.searchPhotos(search);

        model.addAttribute("images", searchedPhotos);

        return "home :: image-container";

    }

}
