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.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
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.DeleteMapping;
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.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import com.example.domain.Shoes;
import com.example.domain.User;
import com.example.service.LoginUser;
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, @Validated ShoesForm form, BindingResult result, MultipartFile multipartFile, @AuthenticationPrincipal LoginUser loginUser) {
		List<Shoes>shoes = shoesService.findAll();
		model.addAttribute("shoes", shoes);
		List<User> users = loginUserDetailsService.findAll();
		model.addAttribute("users",  users);
		User user = loginUser.getUser();
		model.addAttribute("user", user);
		return "management";
	}
	
	//靴の登録処理
	@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 + oldFileName)));
//		        BufferedOutputStream stream = new BufferedOutputStream(
//		        		new FileOutputStream(new File(uploadPath + newFileName)));
		        stream.write(bytes);
		        stream.close();
		 
		        // 圧縮
		        //File input = new File(uploadPath + newFileName);
		        File input = new File(uploadPath + oldFileName);
		        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());
		        shoes.setPhoto(oldFileName.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.getProductStatus());
		shoesService.update(shoes);
		//遷移先 
		return "redirect:/limited/admin/management";
	}
	//商品編集画面
	@GetMapping(path = "{id}/edit")
	String editForm(@PathVariable Integer id, ShoesForm form, Model model){
		Shoes shoes = shoesService.findOne(id);
		model.addAttribute("shoes", shoes);
		BeanUtils.copyProperties(shoes, form);
		return "shoeEdit";
	}
	//商品編集機能
	@PostMapping(path = "{id}/edit")
	String edit(@PathVariable Integer id, @Validated ShoesForm form, BindingResult result, Model model, MultipartFile multipartFile) throws Exception {
//		if(result.hasErrors()) {
//			return editForm(id, form, model);
//		}
		
		Shoes shoes = new Shoes();
		if(result.hasErrors()) {
			return "management";
		}
		multipartFile = form.getMultipartFile();

		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 + oldFileName)));
//		        BufferedOutputStream stream = new BufferedOutputStream(
//		        		new FileOutputStream(new File(uploadPath + newFileName)));
		        stream.write(bytes);
		        stream.close();
		 
		        // 圧縮
		        //File input = new File(uploadPath + newFileName);
		        File input = new File(uploadPath + oldFileName);
		        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());
		        shoes.setPhoto(oldFileName.toString());
		 
		    } catch (Exception e) {
		        System.out.println(e);
		    }
		}
		shoes.setId(id);
		shoes.setName(form.getName());
		shoes.setPrice(form.getPrice());
		shoes.setStock(form.getStock());
		shoes.setSize(form.getSize());
		shoes.setProductStatus(form.getProductStatus());
	
		shoesService.update(shoes);
		return "redirect:/limited/admin/management";
	}
	
	//商品削除
	@DeleteMapping(path = "{id}")
	String delete(@PathVariable Integer id) {
		shoesService.delete(id);
		return "redirect:/limited/admin/management";
	}
	
	//user権限変更
	@PostMapping(path = "{id}")
	String changeRoles(Integer id, @AuthenticationPrincipal LoginUser loginUser){
		User user = loginUserDetailsService.findOne(id);
		String role = user.getRoles();
		if(role.equals("ADMIN")){
			user.setRoles("USER");
		}else{
			user.setRoles("ADMIN");
		}
		loginUserDetailsService.create(user);
		return "redirect:/limited/admin/management";
	}
	

}
