package com.apobates.forum.thrones.admin.controller;

import com.apobates.forum.event.elderly.ActionEventCulpritor;
import com.apobates.forum.member.entity.Member;
import com.apobates.forum.member.entity.MemberRoleEnum;
import com.apobates.forum.member.service.MemberService;
import com.apobates.forum.member.storage.OnlineMemberStorage;
import com.apobates.forum.member.storage.core.MemberSessionBean;
import com.apobates.forum.thrones.admin.controller.form.LoginForm;
import com.apobates.forum.utils.Commons;
import java.util.Optional;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * 管理端主控制器
 *
 * @author xiaofanku
 * @since 20200603
 */
@Controller
public class AdminHomeController {
    @Autowired
    private MemberService memberService;
    @Autowired
    private OnlineMemberStorage onlineMemberStorage;
    @Value("${site.domain}")
    private String siteDomain;
    @Value("${web.view.index}")
    private String defPath;
    private final static Logger logger = LoggerFactory.getLogger(AdminHomeController.class);
    
    // 跳转到版块首页
    @GetMapping(path = "/")
    public String home(
            @RequestParam(value = "from", required = false, defaultValue = "") String fromPath,
            MemberSessionBean mbean,
            HttpServletRequest request,
            Model model) {
        try {
            // 在线的状态下无需登录
            if (mbean.isOnline() && MemberRoleEnum.ADMIN == mbean.getRole()) {
                return "redirect:/client";
            }
        } catch (NullPointerException e) {}
        //
        LoginForm form = new LoginForm();
        String A = Commons.isNotBlank(fromPath) ? fromPath : Commons.getNativeURL(request.getHeader("referer"), siteDomain, defPath);
        form.setRedirect(A);
        form.setLexical("tmp" + Commons.randomAlphaNumeric(12));
        model.addAttribute("form", form);
        return "admin/member/login";
    }
    
    // 登录
    @PostMapping(path = "/")
    public String login(
            HttpServletRequest request,
            HttpServletResponse response,
            @Valid @ModelAttribute("form") LoginForm form,
            BindingResult bindingResult,
            Model model) {
        if (bindingResult.hasErrors()) {
            model.addAttribute("form", form);
            model.addAttribute("errors", bindingResult.getAllErrors().get(0).getDefaultMessage());
            return "admin/member/login";
        }
        Optional<Member> rm = memberService.signIn(form.getNames(), form.getPswd(), true, AdminMemberController.getDescriptorInstance(request, form.getToken()));
        if (!rm.isPresent()) {
            model.addAttribute("form", form);
            model.addAttribute("errors", "会员不存在或密码错误");
            return "admin/member/login";
        }
        Member m = rm.get();
        MemberSessionBean mbean = new MemberSessionBean(m, form.getRequestIpAddr(request));
        
        onlineMemberStorage.store(mbean, request, response);
        return "redirect:/client";
    }
    
    // 根据组不同显示不同的欢迎界面
    @GetMapping(path = "/client")
    public String clientMain(MemberSessionBean mbean, HttpServletRequest request, HttpSession session, Model model) {
        return "redirect:/starter";
    }
    
    @GetMapping(path = "/starter")
    public String welcome(HttpServletRequest request, Model model) {
        return "admin/starter";
    }
    
    // 退出系统
    @GetMapping(path = "/offline.xhtml")
    public String signout(
            MemberSessionBean mbean,
            HttpServletRequest request,
            HttpServletResponse response,
            HttpSession session,
            Model model) {
        if (mbean.isOnline()) {
            session.invalidate();
            // ----------------------------------------移除Cookie
            onlineMemberStorage.delete(request, response);
        }
        return "admin/member/logout";
    }
    
    public static ActionEventCulpritor getActionCulpritor(long memberId, String memberNickname, HttpServletRequest request, String token){
        return new ActionEventCulpritor() {
            @Override
            public long getMemberId() {
                return memberId;
            }
            
            @Override
            public String getMemberNickname() {
                return memberNickname;
            }
            
            @Override
            public String getIpAddr() {
                return Commons.getRemoteAddr(request);
            }
            
            @Override
            public String getToken() {
                return token;
            }
            
            @Override
            public String getUserAgent() {
                return request.getHeader("User-Agent");
            }
        };
    }
}