package com.xkrs.controller;

import com.xkrs.common.encapsulation.PromptMessageEnum;
import nl.basjes.parse.useragent.UserAgent;
import nl.basjes.parse.useragent.UserAgentAnalyzer;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Locale;

import static com.xkrs.common.encapsulation.OutputEncapsulation.outputEncapsulationObject;

/**
 * 系统管理测试服务
 * @author tajochen
 */
@RestController
@RequestMapping(value = "/api")
public class SysManageController {

    @RequestMapping(value="/hello/role",method = RequestMethod.GET)
    @PreAuthorize("hasAnyRole('role_administor','role_system_manager')")
    public String hello() {
        //获取区域信息
        Locale locale = LocaleContextHolder.getLocale();
        return outputEncapsulationObject(PromptMessageEnum.SUCCESS,"hello vip",locale);
    }

    @RequestMapping(value="/hello/auth",method = RequestMethod.GET)
    @PreAuthorize("hasAnyAuthority('auth_system_manager','auth_general_user')")
    public String world() {
        //获取区域信息
        Locale locale = LocaleContextHolder.getLocale();
        return outputEncapsulationObject(PromptMessageEnum.SUCCESS,"world",locale);
    }

    @RequestMapping(value="/greeting",method = RequestMethod.GET)
    public String greeting(@RequestParam(required=false, defaultValue="World") String name,
                           @RequestHeader(value="User-Agent") String userAgent) {
        //获取区域信息
        Locale locale = LocaleContextHolder.getLocale();
        System.out.println("==== in greeting ====");
        System.out.println(userAgent);
        UserAgentAnalyzer uaa = UserAgentAnalyzer
                .newBuilder()
                .hideMatcherLoadStats()
                .withCache(10000)
                .build();

        UserAgent agent = uaa.parse(userAgent);
        for (String fieldName: agent.getAvailableFieldNamesSorted()) {
            System.out.println(fieldName + " = " + agent.getValue(fieldName));
        }
        return outputEncapsulationObject(PromptMessageEnum.SUCCESS,name,locale);
    }
}
