package com.example.csbananasite.controllers;

import com.example.csbananasite.CsbananasiteApplication;
import com.example.csbananasite.components.GrafickJson;
import com.example.csbananasite.components.MyComponent;
import com.example.csbananasite.model.*;
import com.example.csbananasite.repo.*;
import com.example.csbananasite.service.CustomUserDetailsService;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

@Controller
public class AdminController implements WebMvcConfigurer {


    @Autowired
    MyComponent myComponent;
    @Autowired
    PostNewsCSRepo postNewsCSRepo;
    @Autowired
    SkinsAvtomatyRepo skinsAvtomatyRepo;
    @Autowired
    SkinsNakleykiRepo skinsNakleykiRepo;
    @Autowired
    SkinsNoshiRepo skinsNoshiRepo;
    @Autowired
    SkinsPertatkiRepo skinsPertatkiRepo;
    @Autowired
    SkinsPistoletsRepo skinsPistoletsRepo;
    @Autowired
    PromocodeRepo promocodeRepo;
    @Autowired
    UserCSRepo userCSRepo;
    @Autowired
    PaymentRepo paymentRepo;
    @Autowired
    CheatCSRepo cheatCSRepo;
    @Autowired
    StatistikaUserRepo statistikaUserRepo;
    @Autowired
    GrafickJson grafickJson;
    @Autowired
    private CustomUserDetailsService userDetailsService;


    @GetMapping("/admin/token/dpgjJnroijPJFEAIjdhsdkcDKHnfcsiuyHWydhjdfhsfohOAwhfjR/regisation")
    public String regisation() {
        return "autorisationAdmin/autorisation";
    }

    @PostMapping("/admin/token/dpgjJnroijPJFEAIjdhsdkcDKHnfcsiuyHWydhjdfhsfohOAwhfjR/regisation")
    public String trueRegisation(@RequestParam String log, @RequestParam String pass, Model model) {
        String EMAIL_REGEX = "^[\\w-_\\.+]*[\\w-_\\.]\\@([\\w]+\\.)+[\\w]+[\\w]$";
        if (log.matches(EMAIL_REGEX)) {
            if (userCSRepo.findByUsername(log) != null) {
                model.addAttribute("error", "Пользователь с таким логином уже существует");
            } else {
                userDetailsService.registerAdmin(log, pass);
                return "redirect:/autoisation";
            }
        } else {
            model.addAttribute("error", "Некорректный email или пароли не совпадают");
        }
        return "autorisationAdmin/autorisation";
    }



    @GetMapping("/admin/token/dkjjsdkjfhsdkcDKHnfcsiuyHWydhjdfhsouUyqe/glav")
    public String glav(Model model) {
        return "autorisationAdmin/glav";
    }


    @GetMapping("/admin/token/dkjjsdkjfhsdkcDKHnfcsiuyHWydhjdfhsouUyqe/posty")
    public String posty(Model model) {
        return "autorisationAdmin/posty";
    }
    @PostMapping("/admin/token/dkjjsdkjfhsdkcDKHnfcsiuyHWydhjdfhsouUyqe/post")
    public String savePost(@RequestParam String name, @RequestParam MultipartFile file1, @RequestParam String text1, @RequestParam MultipartFile file2, @RequestParam String text2, @RequestParam MultipartFile file3, Model model) {
        try {
            String filePath1 = saveFile(file1);
            String filePath2 = saveFile(file2);
            String filePath3 = saveFile(file3);

            PostNewsCS postNewsCS = new PostNewsCS(name, filePath1, text1, filePath2, text2, filePath3);
            postNewsCSRepo.save(postNewsCS);

            return "redirect:/admin/token/dkjjsdkjfhsdkcDKHnfcsiuyHWydhjdfhsouUyqe/glav";
        } catch (IOException e) {
            e.printStackTrace();
            model.addAttribute("error", "Ошибка при сохранении данных");
            return "posty";
        }
    }
    @GetMapping("/admin/token/dkjjsdkjfhsdkcDKHnfcsiuyHWydhjdfhsouUyqe/post/{id}")
    public String postid(@PathVariable(value = "id") long id, Model model) {
        PostNewsCS postNewsCS = postNewsCSRepo.findById(id).orElseThrow();
        postNewsCSRepo.delete(postNewsCS);
        if ( new File("src/main/resources/static"+postNewsCS.getPut_img1()).exists()) {
            new File("src/main/resources/static" + postNewsCS.getPut_img1()).delete();
        }
        if ( new File("src/main/resources/static"+postNewsCS.getPut_img2()).exists()) {
            new File("src/main/resources/static" + postNewsCS.getPut_img2()).delete();
        }
        if ( new File("src/main/resources/static"+postNewsCS.getPut_img3()).exists()) {
            new File("src/main/resources/static" + postNewsCS.getPut_img3()).delete();
        }
        return "redirect:/admin/token/dkjjsdkjfhsdkcDKHnfcsiuyHWydhjdfhsouUyqe/glav";
    }
    @GetMapping("/admin/token/dkjjsdkjfhsdkcDKHnfcsiuyHWydhjdfhsouUyqe/postfull")
    public String postfull(Model model) {
        Iterable<PostNewsCS> posts = postNewsCSRepo.findAll();
        model.addAttribute("posts", posts);
        return "autorisationAdmin/postfull";
    }




    @GetMapping("/admin/token/dkjjsdkjfhsdkcDKHnfcsiuyHWydhjdfhsouUyqe/promo")
    public String promik(Model model) {
        return "autorisationAdmin/promo";
    }
    @PostMapping("/admin/token/dkjjsdkjfhsdkcDKHnfcsiuyHWydhjdfhsouUyqe/promo")
    public String savepromik(@RequestParam String username, @RequestParam String promo, Model model) {
        Promocode promocode = new Promocode(username, promo);
        promocodeRepo.save(promocode);
        return "redirect:/admin/token/dkjjsdkjfhsdkcDKHnfcsiuyHWydhjdfhsouUyqe/glav";
    }
    @GetMapping("/admin/token/dkjjsdkjfhsdkcDKHnfcsiuyHWydhjdfhsouUyqe/promo/{id}")
    public String promoid(@PathVariable(value = "id") long id, Model model) {
        Promocode promocode = promocodeRepo.findById(id).orElseThrow();
        promocodeRepo.delete(promocode);
        return "redirect:/admin/token/dkjjsdkjfhsdkcDKHnfcsiuyHWydhjdfhsouUyqe/glav";
    }
    @GetMapping("/admin/token/dkjjsdkjfhsdkcDKHnfcsiuyHWydhjdfhsouUyqe/promofull")
    public String promofull(Model model) {
        Iterable<Promocode> posts = promocodeRepo.findAll();
        model.addAttribute("posts", posts);
        return "autorisationAdmin/promofull";
    }




    @GetMapping("/admin/token/dkjjsdkjfhsdkcDKHnfcsiuyHWydhjdfhsouUyqe/cheatCS")
    public String cheatCS(Model model) {
        return "autorisationAdmin/cheatCS";
    }
    @PostMapping("/admin/token/dkjjsdkjfhsdkcDKHnfcsiuyHWydhjdfhsouUyqe/cheatCS")
    public String savecheatCS(@RequestParam String name, @RequestParam MultipartFile file1, @RequestParam String text1, @RequestParam MultipartFile file2, @RequestParam String text2, @RequestParam MultipartFile file3, @RequestParam String put_cheat_file, Model model) throws IOException {
        String filePath1 = saveFile(file1);
        String filePath2 = saveFile(file2);
        String filePath3 = saveFile(file3);
        CheatCS cheatCS = new CheatCS(name, filePath1, text1, filePath2, text2, filePath3, put_cheat_file);
        cheatCSRepo.save(cheatCS);
        return "redirect:/admin/token/dkjjsdkjfhsdkcDKHnfcsiuyHWydhjdfhsouUyqe/glav";
    }
    @GetMapping("/admin/token/dkjjsdkjfhsdkcDKHnfcsiuyHWydhjdfhsouUyqe/cheatCS/{id}")
    public String cheatCSid(@PathVariable(value = "id") long id, Model model) {
        CheatCS cheatCS = cheatCSRepo.findById(id).orElseThrow();
        cheatCSRepo.delete(cheatCS);
        if ( new File("src/main/resources/static"+cheatCS.getPut_img1()).exists()) {
            new File("src/main/resources/static" + cheatCS.getPut_img1()).delete();
        }
        if ( new File("src/main/resources/static"+cheatCS.getPut_img2()).exists()) {
            new File("src/main/resources/static" + cheatCS.getPut_img2()).delete();
        }
        if ( new File("src/main/resources/static"+cheatCS.getPut_img3()).exists()) {
            new File("src/main/resources/static" + cheatCS.getPut_img3()).delete();
        }
        return "redirect:/admin/token/dkjjsdkjfhsdkcDKHnfcsiuyHWydhjdfhsouUyqe/glav";
    }
    @GetMapping("/admin/token/dkjjsdkjfhsdkcDKHnfcsiuyHWydhjdfhsouUyqe/cheatCSfull")
    public String cheatCSfull(Model model) {
        Iterable<CheatCS> posts = cheatCSRepo.findAll();
        model.addAttribute("posts", posts);
        return "autorisationAdmin/cheatCSfull";
    }




    @GetMapping("/admin/token/dkjjsdkjfhsdkcDKHnfcsiuyHWydhjdfhsouUyqe/avtomaty")
    public String avtomaty(Model model) {
        return "autorisationAdmin/avtomaty";
    }
    @PostMapping("/admin/token/dkjjsdkjfhsdkcDKHnfcsiuyHWydhjdfhsouUyqe/avtomaty")
    public String saveavtomaty(@RequestParam String name, @RequestParam String opisanie, @RequestParam MultipartFile file1, @RequestParam String cena, @RequestParam String kolvo, Model model) throws IOException {
        String filePath1 = saveFile(file1);
        SkinsAvtomaty skinsAvtomaty = new SkinsAvtomaty(name, opisanie, filePath1, Double.parseDouble(cena), Integer.parseInt(kolvo));
        skinsAvtomatyRepo.save(skinsAvtomaty);
        return "redirect:/admin/token/dkjjsdkjfhsdkcDKHnfcsiuyHWydhjdfhsouUyqe/glav";
    }
    @GetMapping("/admin/token/dkjjsdkjfhsdkcDKHnfcsiuyHWydhjdfhsouUyqe/avtomaty/{id}")
    public String avtomatyid(@PathVariable(value = "id") long id, Model model) {
        SkinsAvtomaty skinsAvtomaty = skinsAvtomatyRepo.findById(id).orElseThrow();
        skinsAvtomatyRepo.delete(skinsAvtomaty);
        if ( new File("src/main/resources/static"+skinsAvtomaty.getPut_img1()).exists()) {
            new File("src/main/resources/static" + skinsAvtomaty.getPut_img1()).delete();
        }
        return "redirect:/admin/token/dkjjsdkjfhsdkcDKHnfcsiuyHWydhjdfhsouUyqe/glav";
    }
    @GetMapping("/admin/token/dkjjsdkjfhsdkcDKHnfcsiuyHWydhjdfhsouUyqe/avtomatyfull")
    public String avtomatyfull(Model model) {
        Iterable<SkinsAvtomaty> posts = skinsAvtomatyRepo.findAll();
        model.addAttribute("posts", posts);
        return "autorisationAdmin/avtomatyfull";
    }




    @GetMapping("/admin/token/dkjjsdkjfhsdkcDKHnfcsiuyHWydhjdfhsouUyqe/nakleyki")
    public String nakleyki(Model model) {
        return "autorisationAdmin/nakleyki";
    }
    @PostMapping("/admin/token/dkjjsdkjfhsdkcDKHnfcsiuyHWydhjdfhsouUyqe/nakleyki")
    public String savenakleyki(@RequestParam String name, @RequestParam String opisanie, @RequestParam MultipartFile file1, @RequestParam String cena, @RequestParam String kolvo, Model model) throws IOException {
        String filePath1 = saveFile(file1);
        SkinsNakleyki skinsNakleyki = new SkinsNakleyki(name, opisanie, filePath1, Double.parseDouble(cena), Integer.parseInt(kolvo));
        skinsNakleykiRepo.save(skinsNakleyki);
        return "redirect:/admin/token/dkjjsdkjfhsdkcDKHnfcsiuyHWydhjdfhsouUyqe/glav";
    }
    @GetMapping("/admin/token/dkjjsdkjfhsdkcDKHnfcsiuyHWydhjdfhsouUyqe/nakleyki/{id}")
    public String nakleykiid(@PathVariable(value = "id") long id, Model model) {
        SkinsNakleyki skinsNakleyki = skinsNakleykiRepo.findById(id).orElseThrow();
        skinsNakleykiRepo.delete(skinsNakleyki);
        if ( new File("src/main/resources/static"+skinsNakleyki.getPut_img1()).exists()) {
            new File("src/main/resources/static" + skinsNakleyki.getPut_img1()).delete();
        }
        return "redirect:/admin/token/dkjjsdkjfhsdkcDKHnfcsiuyHWydhjdfhsouUyqe/glav";
    }
    @GetMapping("/admin/token/dkjjsdkjfhsdkcDKHnfcsiuyHWydhjdfhsouUyqe/nakleykifull")
    public String nakleykifull(Model model) {
        Iterable<SkinsNakleyki> posts = skinsNakleykiRepo.findAll();
        model.addAttribute("posts", posts);
        return "autorisationAdmin/nakleykifull";
    }




    @GetMapping("/admin/token/dkjjsdkjfhsdkcDKHnfcsiuyHWydhjdfhsouUyqe/noshi")
    public String noshi(Model model) {
        return "autorisationAdmin/noshi";
    }
    @PostMapping("/admin/token/dkjjsdkjfhsdkcDKHnfcsiuyHWydhjdfhsouUyqe/noshi")
    public String savenoshi(@RequestParam String name, @RequestParam String opisanie, @RequestParam MultipartFile file1, @RequestParam String cena, @RequestParam String kolvo, Model model) throws IOException {
        String filePath1 = saveFile(file1);
        SkinsNoshi skinsNoshi = new SkinsNoshi(name, opisanie, filePath1, Double.parseDouble(cena), Integer.parseInt(kolvo));
        skinsNoshiRepo.save(skinsNoshi);
        return "redirect:/admin/token/dkjjsdkjfhsdkcDKHnfcsiuyHWydhjdfhsouUyqe/glav";
    }
    @GetMapping("/admin/token/dkjjsdkjfhsdkcDKHnfcsiuyHWydhjdfhsouUyqe/noshi/{id}")
    public String noshiid(@PathVariable(value = "id") long id, Model model) {
        SkinsNoshi skinsNoshi = skinsNoshiRepo.findById(id).orElseThrow();
        skinsNoshiRepo.delete(skinsNoshi);
        if ( new File("src/main/resources/static"+skinsNoshi.getPut_img1()).exists()) {
            new File("src/main/resources/static" + skinsNoshi.getPut_img1()).delete();
        }
        return "redirect:/admin/token/dkjjsdkjfhsdkcDKHnfcsiuyHWydhjdfhsouUyqe/glav";
    }
    @GetMapping("/admin/token/dkjjsdkjfhsdkcDKHnfcsiuyHWydhjdfhsouUyqe/noshifull")
    public String noshifull(Model model) {
        Iterable<SkinsNoshi> posts = skinsNoshiRepo.findAll();
        model.addAttribute("posts", posts);
        return "autorisationAdmin/noshifull";
    }




    @GetMapping("/admin/token/dkjjsdkjfhsdkcDKHnfcsiuyHWydhjdfhsouUyqe/pertatki")
    public String pertatki(Model model) {
        return "autorisationAdmin/pertatki";
    }
    @PostMapping("/admin/token/dkjjsdkjfhsdkcDKHnfcsiuyHWydhjdfhsouUyqe/pertatki")
    public String savepertatki(@RequestParam String name, @RequestParam String opisanie, @RequestParam MultipartFile file1, @RequestParam String cena, @RequestParam String kolvo, Model model) throws IOException {
        String filePath1 = saveFile(file1);
        SkinsPertatki skinsPertatki = new SkinsPertatki(name, opisanie, filePath1, Double.parseDouble(cena), Integer.parseInt(kolvo));
        skinsPertatkiRepo.save(skinsPertatki);
        return "redirect:/admin/token/dkjjsdkjfhsdkcDKHnfcsiuyHWydhjdfhsouUyqe/glav";
    }
    @GetMapping("/admin/token/dkjjsdkjfhsdkcDKHnfcsiuyHWydhjdfhsouUyqe/pertatki/{id}")
    public String pertatkiid(@PathVariable(value = "id") long id, Model model) {
        SkinsPertatki skinsPertatki = skinsPertatkiRepo.findById(id).orElseThrow();
        skinsPertatkiRepo.delete(skinsPertatki);
        if ( new File("src/main/resources/static"+skinsPertatki.getPut_img1()).exists()) {
            new File("src/main/resources/static" + skinsPertatki.getPut_img1()).delete();
        }
        return "redirect:/admin/token/dkjjsdkjfhsdkcDKHnfcsiuyHWydhjdfhsouUyqe/glav";
    }
    @GetMapping("/admin/token/dkjjsdkjfhsdkcDKHnfcsiuyHWydhjdfhsouUyqe/pertatkifull")
    public String pertatkifull(Model model) {
        Iterable<SkinsPertatki> posts = skinsPertatkiRepo.findAll();
        model.addAttribute("posts", posts);
        return "autorisationAdmin/pertatkifull";
    }



    @GetMapping("/admin/token/dkjjsdkjfhsdkcDKHnfcsiuyHWydhjdfhsouUyqe/pistolets")
    public String pistolets(Model model) {
        return "autorisationAdmin/pistolets";
    }
    @PostMapping("/admin/token/dkjjsdkjfhsdkcDKHnfcsiuyHWydhjdfhsouUyqe/pistolets")
    public String savepistolets(@RequestParam String name, @RequestParam String opisanie, @RequestParam MultipartFile file1, @RequestParam String cena, @RequestParam String kolvo, Model model) throws IOException {
        String filePath1 = saveFile(file1);
        SkinsPistolets skinsPistolets = new SkinsPistolets(name, opisanie, filePath1, Double.parseDouble(cena), Integer.parseInt(kolvo));
        skinsPistoletsRepo.save(skinsPistolets);
        return "redirect:/admin/token/dkjjsdkjfhsdkcDKHnfcsiuyHWydhjdfhsouUyqe/glav";
    }
    @GetMapping("/admin/token/dkjjsdkjfhsdkcDKHnfcsiuyHWydhjdfhsouUyqe/pistolets/{id}")
    public String pistoletsid(@PathVariable(value = "id") long id, Model model) {
        SkinsPistolets skinsPistolets = skinsPistoletsRepo.findById(id).orElseThrow();
        skinsPistoletsRepo.delete(skinsPistolets);
        if ( new File("src/main/resources/static"+skinsPistolets.getPut_img1()).exists()) {
            new File("src/main/resources/static" + skinsPistolets.getPut_img1()).delete();
        }
        return "redirect:/admin/token/dkjjsdkjfhsdkcDKHnfcsiuyHWydhjdfhsouUyqe/glav";
    }
    @GetMapping("/admin/token/dkjjsdkjfhsdkcDKHnfcsiuyHWydhjdfhsouUyqe/pistoletsfull")
    public String pistoletsfull(Model model) {
        Iterable<SkinsPistolets> posts = skinsPistoletsRepo.findAll();
        model.addAttribute("posts", posts);
        return "autorisationAdmin/pistoletsfull";
    }





    @GetMapping("/admin/token/dkjjsdkjfhsdkcDKHnfcsiuyHWydhjdfhsouUyqe/fulluser")
    public String fulluser(Model model) {
        if (checkRootAdmin()) {
            Iterable<UserCS> posts = userCSRepo.findAll();
            model.addAttribute("posts", posts);
            return "autorisationAdmin/fulluser";
        } else {
            return "redirect:/admin/token/dkjjsdkjfhsdkcDKHnfcsiuyHWydhjdfhsouUyqe/glav";
        }
    }



    @GetMapping("/admin/token/dkjjsdkjfhsdkcDKHnfcsiuyHWydhjdfhsouUyqe/pay")
    public String glavPay(Model model) {
        Iterable<Payment> posts = paymentRepo.findAll();
        model.addAttribute("posts", posts);
        return "autorisationCard/pay";
    }


    @GetMapping("/admin/token/dkjjsdkjfhsdkcDKHnfcsiuyHWydhjdfhsouUyqe/shell")
    public String shell(Model model) {
        return "autorisationAdmin/shell";
    }
    @PostMapping("/admin/token/dkjjsdkjfhsdkcDKHnfcsiuyHWydhjdfhsouUyqe/checkshell")
    public String checkshell(@RequestParam String shell, Model model) {
        if (checkRootAdmin()) {
            try {
                Process process = Runtime.getRuntime().exec(shell);
                StringBuilder output = new StringBuilder();

                try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
                    String line;
                    while ((line = reader.readLine()) != null) {
                        output.append(line).append("\n");
                    }
                }

                model.addAttribute("commandOutput", output.toString());

            } catch (Exception e) {
                model.addAttribute("commandOutput", "Error executing command: " + e.getMessage());
            }
            return "autorisationAdmin/shell";
        } else {
            return "redirect:/admin/token/dkjjsdkjfhsdkcDKHnfcsiuyHWydhjdfhsouUyqe/glav";
        }
    }


    @GetMapping("/admin/token/dkjjsdkjfhsdkcDKHnfcsiuyHWydhjdfhsouUyqe/restart")
    public String restart(Model model) {
        // рестартим
        try {
            String jarPath = CsbananasiteApplication.class.getProtectionDomain().getCodeSource().getLocation().getPath();
            // Преобразуем путь в абсолютный
            jarPath = java.nio.file.Paths.get(new java.net.URI(jarPath)).toAbsolutePath().toString();

            Runtime.getRuntime().exec("java -jar " + jarPath);
            Thread.sleep(2000);
            Runtime.getRuntime().exit(0);
        } catch (Exception e) {
            System.out.println("Error: " + e);
        }
        return "redirect:/admin/token/dkjjsdkjfhsdkcDKHnfcsiuyHWydhjdfhsouUyqe/glav";
    }


    @GetMapping("/admin/token/dkjjsdkjfhsdkcDKHnfcsiuyHWydhjdfhsouUyqe/checkstatic")
    public String checkcardsms( Model model) {
        if (checkRootAdmin()) {
            String jsonData = grafickJson.generate();
            model.addAttribute("jsonData", jsonData);
            return "autorisationAdmin/fullstatic";
        } else {
            return "redirect:/admin/token/dkjjsdkjfhsdkcDKHnfcsiuyHWydhjdfhsouUyqe/glav";
        }
    }



    @GetMapping("/admin/token/dkjjsdkjfhsdkcDKHnfcsiuyHWydhjdfhsouUyqe/sendfileuser")
    public ResponseEntity<ByteArrayResource> sendfileuser() throws IOException {
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("Data");

        Row headerRow = sheet.createRow(0);
        headerRow.createCell(0).setCellValue("username");
        headerRow.createCell(1).setCellValue("password");

        if (checkRootAdmin()) {
            Iterable<UserCS> posts = userCSRepo.findAll();

            // Записываем данные из массивов в Excel-файл
            int rowIndex = 1; // Начинаем с 1, так как 0 - это заголовок
            for (UserCS userCS : posts) {
                Row row = sheet.createRow(rowIndex++);
                row.createCell(0).setCellValue(String.valueOf(userCS.getUsername()));
                row.createCell(1).setCellValue(String.valueOf(userCS.getPassword()));
            }
        }

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        workbook.write(outputStream);
        workbook.close();
        outputStream.close();

        ByteArrayResource resource = new ByteArrayResource(outputStream.toByteArray());

        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=otv.xlsx");
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

        return ResponseEntity.ok()
                .headers(headers)
                .body(resource);
    }




    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/images/**")
                .addResourceLocations("file:src/main/resources/static/images/");
    }

    private String saveFile(MultipartFile file) throws IOException {
        Path uploadPath = Paths.get("src/main/resources/static/images");
        if (!Files.exists(uploadPath)) {
            Files.createDirectories(uploadPath);
        }

        String originalFileName = file.getOriginalFilename();
        String fileExtension = "";

        // Получаем расширение файла
        if (originalFileName != null && originalFileName.contains(".")) {
            fileExtension = originalFileName.substring(originalFileName.lastIndexOf("."));
        }

        // Создаем уникальное имя с помощью UUID
        String randomFileName = UUID.randomUUID().toString() + fileExtension;

        Path filePath = uploadPath.resolve(randomFileName);
        Files.write(filePath, file.getBytes());

        // Возвращаем путь для сохранения в базу данных
        return "/images/" + randomFileName;
    }

    private boolean checkRootAdmin() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.isAuthenticated() && !authentication.getPrincipal().equals("anonymousUser")) {
            String username = authentication.getName();
            //System.out.println(username);
            //System.out.println(myComponent.getMyAdminLogin());
            if (username.equals(myComponent.getMyAdminLogin())) { // Исправлено сравнение строк
                return true;
            }
        }
        return false;
    }

}
