package kr.co.jinwoosi.clfd.clfd.prod.web;

import kr.co.jinwoosi.clfd.clfd.prod.service.ProdLikeService;
import kr.co.jinwoosi.clfd.framework.security.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;

@Controller
public class ProdLikeController {

    @Autowired
    private ProdLikeService prodLikeService;

    @RequestMapping(value = "/clfd/prod/like.json", method = RequestMethod.POST)
    @ResponseBody
    public HashMap<String, Object> prodLike(HttpServletRequest request,
                                            @RequestParam(value = "prodId") String prodId,
                                            @RequestParam(value = "like") Boolean like) {
        HashMap<String, Object> result = new HashMap<>();
        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            result.put("result", "fail");
            result.put("message", "회원만 이용 가능한 서비스입니다.");
            return result;
        }

        if (like) {
            try {
                prodLikeService.insert(Long.parseLong(prodId), user.getUserId());
            } catch (RuntimeException e) {
                result.put("result", "fail");
                result.put("message", e.getMessage());
            }
        } else {
            try {
                prodLikeService.delete(Long.parseLong(prodId), user.getUserId());
            } catch (RuntimeException e) {
                result.put("result", "fail");
                result.put("message", e.getMessage());
            }
        }
        result.put("result", "success");
        result.put("like", like);
        return result;
    }

}
