package com.example.web;

import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.List;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.plugins.jpeg.JPEGImageWriteParam;
import javax.imageio.stream.ImageOutputStream;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import com.example.domain.Shoes;
import com.example.domain.User;
import com.example.service.LoginUserDetailsService;
import com.example.service.ShoesService;

//管理画面用
@Controller
@RequestMapping("limited/admin/management/")
public class ManagementController {
	@Autowired
	ShoesService shoesService;
	@Autowired
	LoginUserDetailsService loginUserDetailsService;
	
	//管理画面表示(靴もユーザ情報も一覧で取得できるようになっている)
	@GetMapping()
	public String management(Model model) {
		List<Shoes>shoes = shoesService. findAll();
		model.addAttribute("shoes", shoes);
		List<User> user = loginUserDetailsService.findAll();
		model.addAttribute("user",  user);
		//遷移先 未設定
		return "Hello World";
	}
	
	//靴の登録処理
		@PostMapping("addShoes")
		public String CreateShoes(@Validated ShoesForm form, BindingResult result, MultipartFile multipartFile) throws Exception {
			if(result.hasErrors()) {
				return "management";
			}
			multipartFile = form.getMultipartFile();
			Shoes shoes = new Shoes();
			if (!multipartFile.isEmpty()) {
		        try {
		            // ファイル名をリネイム
		            File oldFileName = new File(multipartFile.getOriginalFilename());
		            File newFileName = new File(oldFileName + ".jpg");
		            oldFileName.renameTo(newFileName);
		 
		            // 保存先を定義
		            String uploadPath = "src/main/resources/static/upload/";
		            byte[] bytes = multipartFile.getBytes();
		 
		            // 指定ファイルへ読み込みファイルを書き込み
		            BufferedOutputStream stream = new BufferedOutputStream(
		                    new FileOutputStream(new File(uploadPath + newFileName)));
		            stream.write(bytes);
		            stream.close();
		 
		            // 圧縮
		            File input = new File(uploadPath + newFileName);
		            BufferedImage image = ImageIO.read(input);
		            OutputStream os = new FileOutputStream(input);
		            Iterator<ImageWriter> writers = ImageIO
		                    .getImageWritersByFormatName("jpg");
		            ImageWriter writer = (ImageWriter) writers.next();
		            ImageOutputStream ios = ImageIO.createImageOutputStream(os);
		            writer.setOutput(ios);
		            ImageWriteParam param = new JPEGImageWriteParam(null);
		            param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
		            param.setCompressionQuality(0.30f);
		            writer.write(null, new IIOImage(image, null, null), param);
		            os.close();
		            ios.close();
		            writer.dispose();
		 
		            // shoes entity に写真の名前を格納する
		            shoes.setPhoto(newFileName.toString());
		 
		        } catch (Exception e) {
		            System.out.println(e);
		        }
		    }
		    shoes.setName(form.getName());
		    shoes.setPrice(form.getPrice());
		    shoes.setStock(form.getStock());
		    shoes.setSize(form.getSize());
		    shoes.setProductStatus(form.getProduct_status());
		    shoesService.update(shoes);
		    //遷移先 未設定
		    return "Hello World";
		}
}
