package com.chantha.springdemo.controller;

import com.chantha.springdemo.model.Product;
import com.chantha.springdemo.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.time.LocalDate;


@Controller
public class ProductController {
    @Autowired
    private  final ProductService productService;

    public ProductController(ProductService productService) {
        this.productService=productService;
    }

    public void uploadFile(MultipartFile file, RedirectAttributes attributes) {
        final String UPLOAD_DIR="E:/Interview/springdemo/src/main/resources/static/img/";
        // normalize the file path
        String fileName = StringUtils.cleanPath(file.getOriginalFilename());

        // save the file on the local file system
        try {
            Path path = Paths.get(UPLOAD_DIR +  LocalDate.now()+fileName);
            Files.copy(file.getInputStream(), path, StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @PostMapping("/admin/product/add")
    public String addProduct(@RequestParam("file") MultipartFile file, @ModelAttribute("product") Product product, RedirectAttributes attributes){
        try {
            if(product.getName().equals("")||product.getColor().equals("")) {
                attributes.addFlashAttribute("message", "Something wrong with your information");
                return "redirect:/admin";
            }
            if(!file.isEmpty()){
                uploadFile(file,attributes);
                product.setImg(StringUtils.cleanPath(LocalDate.now()+file.getOriginalFilename()));
            }
            else{
                product.setImg("default.jpg");
            }
            productService.save(product);
            return "redirect:/admin";
        }catch (Exception ex){
            attributes.addFlashAttribute("message", ex.getMessage());
            return "redirect:/admin";
        }
    }
    @PostMapping("/admin/product/update")
    public String updateProduct(@RequestParam("file") MultipartFile file, @ModelAttribute("product") Product product, RedirectAttributes attributes){
        try {
            if(product.getName().equals("")||product.getColor().equals("")) {
                attributes.addFlashAttribute("message", "Something wrong with your information");
                return "redirect:/admin";
            }
            if(!file.isEmpty()){
                uploadFile(file,attributes);
                product.setImg(StringUtils.cleanPath(LocalDate.now()+file.getOriginalFilename()));
            }
            else{
                Product p=productService.findById(product.getId());
                product.setImg(p.getImg());
            }
            attributes.addFlashAttribute("message", "Update Successfully");
            productService.save(product);
            return "redirect:/admin";
        }catch (Exception ex){
            attributes.addFlashAttribute("message", ex.getMessage());
            return "redirect:/admin";
        }
    }
    @RequestMapping("/admin/product/delete/{id}")
    public String deleteProduct(@PathVariable  Long id, RedirectAttributes attributes)
    {
        try{
            Product pro=productService.findById(id);
            productService.deleteById(id);
            attributes.addFlashAttribute("message","Product name "+pro.getName()+" has delete successfully");
            return "redirect:/admin";
        }catch (Exception ex){
            attributes.addFlashAttribute("message", "Sorry your product not register yet");
            return "redirect:/admin";
        }
    }

}

