package com.itdominator.api.controller;


import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.itdominator.api.dto.ThumbnailDto;
import com.itdominator.api.dto.ThumbnailSearchCriteria;
import com.itdominator.api.entities.Thumbnails;
import com.itdominator.api.services.ThumbnailerService;
import com.itdominator.api.util.Thumbnailer;

import jakarta.validation.Valid;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.Pattern;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;



@RestController
@EnableMethodSecurity(securedEnabled = true, prePostEnabled = true)
@RequiredArgsConstructor
@Slf4j
@Validated
public class ThumbnailerApiController {

    private final ThumbnailerService thumbnailerService;
    private final Thumbnailer thumbnailer;


    @PreAuthorize("hasRole('User')")
    @PostMapping("/get-thumbnail/id/{id}")
    public ThumbnailDto getThumbnailById(
        @PathVariable
        @Min(value = 0L, message = "Can't be negative number...")
        @Max(value = 99999999L, message = "ID too large...") final int id
    ) {
        return thumbnailerService.getThumbnailById(id);
    }

    @PreAuthorize("hasRole('User')")
    @PostMapping("/get-thumbnail/hash/{fileHash}")
    public ThumbnailDto getThumbnailByHash(
        @Pattern(regexp = "[a-zA-Z0-9]{32}*$") @PathVariable("fileHash") final String fileHash
    ) {
        return thumbnailerService.getThumbnailByHash(fileHash);
    }


    @PreAuthorize("hasRole('User')")
    @PostMapping("/get-thumbnail")
    public ThumbnailDto getThumbnailByIdOrHashQuery(
        @Valid @RequestBody ThumbnailSearchCriteria criteria
    ) {
        return thumbnailerService.getThumbnailByIdOrHashQuery(criteria);
    }

    @PreAuthorize("hasRole('Admin')")
    @GetMapping("/get-all-thumbnails")
    public List<ThumbnailDto> getAllThumbnails() {
        return thumbnailerService.getAllThumbnails();
    }

    @PreAuthorize("hasRole('User')")
    @GetMapping("/temp-videos-list-test")
    public Set<String> getAllVideoFiles() throws IOException {
        Set<Path> paths   = thumbnailer.collectVideoFilePaths("/home/abaddon/Downloads");
        Set<String> files = new HashSet<>();

        thumbnailer.generateThumbnails(paths);
        for (Path path : paths) {
            String fileName = path.getFileName().toString();
            String fileHash = DigestUtils.sha256Hex(fileName);

            // files.add( path.getFileName().toString() );
            files.add( path.toString() );

            thumbnailerService.saveThumbnail( 
                new Thumbnails(fileName, fileHash, Files.readAllBytes( Path.of("/tmp/" + fileHash + ".jpg") ) )
            );
        }

        return files;
    }

}
