package com.contract.controller;

import com.contract.entity.UserWatchlist;
import com.contract.entity.resp.MessageResult;
import com.contract.entity.transform.AuthMember;
import com.contract.interceptor.AuthenticationInterceptor;
import com.contract.service.UserWatchlistService;
import com.contract.util.RequestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/watchlist")
public class UserWatchlistController {

    @Autowired
    private UserWatchlistService userWatchlistService;

    @GetMapping("/test")
    public MessageResult test(HttpServletRequest request) {
        String lang = RequestUtils.getLangFromHeader(request);
        return MessageResult.successLang(lang);
    }

    @GetMapping("/list")
    public MessageResult list(HttpSession session, HttpServletRequest request) {
        String lang = RequestUtils.getLangFromHeader(request);
        AuthMember authMember = (AuthMember) session.getAttribute(AuthenticationInterceptor.SESSION_MEMBER);
        List<UserWatchlist> list = userWatchlistService.listByMember(authMember.getId());
        return MessageResult.successLang(lang, list);
    }

    @PostMapping("/add")
    public MessageResult add(@RequestBody UserWatchlist req, HttpSession session, HttpServletRequest request) {
        String lang = RequestUtils.getLangFromHeader(request);
        AuthMember authMember = (AuthMember) session.getAttribute(AuthenticationInterceptor.SESSION_MEMBER);
        userWatchlistService.addWatchlist(authMember.getId(), req.getSymbol());
        return MessageResult.successLang(lang);
    }

    @PostMapping("/cancel")
    public MessageResult cancel(@RequestBody UserWatchlist req, HttpSession session, HttpServletRequest request) {
        String lang = RequestUtils.getLangFromHeader(request);
        AuthMember authMember = (AuthMember) session.getAttribute(AuthenticationInterceptor.SESSION_MEMBER);
        userWatchlistService.cancelWatchlist(authMember.getId(), req.getSymbol());
        return MessageResult.successLang(lang);
    }
}
