package org.laj.web.controller;

import org.laj.web.po.SecKill;
import org.laj.web.service.SecKillService;
import org.laj.web.vo.SecKillExporter;
import org.laj.web.vo.SecKillResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.CacheControl;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.concurrent.TimeUnit;

/**
 *
 * Created by liuanjun on 2017/8/13.
 */
@Controller
@RequestMapping(value = "/secKill")
public class SecKillController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private SecKillService secKillService;

    // problem: 次方法仅作为参考,实际应用中,仅获取列表或者单个记录时用GET
    // 此方法应当使用POST/PUT,参数也不作为url路径(目录),而是RequestParam
    @RequestMapping(value = "/{secKillId}/exporter", method = RequestMethod.GET, produces = {"application/json;charset=utf-8"})
    @ResponseBody
    public SecKillResult<SecKillExporter> export(@PathVariable("secKillId") Long secKillId) {
        //SecKillResult<SecKillExporter> result;
        try {
            SecKillExporter exporter = secKillService.exportSecKill(secKillId);
            return new SecKillResult<>(true, exporter);
        } catch (Exception e) {
            logger.error("{}", e.getMessage());
            return new SecKillResult<>(false, e.getLocalizedMessage());
        }
    }

    // public String ... (Model model ...)

//    POST, PUT等接口 RequestParam(require = false)
//    GET接口,@PathVariable("...")
//    @RequestMapping(value = "/excution", method = RequestMethod.PUT, produces = {"application/json;charset=utf-8"})
//    public SecKillResult<SecKillExecution> excute(@RequestParam(required = false) Long secKillId) {
//        return null;
//    }

    @RequestMapping(value = "/throw")
    public void throwException() {
        throw new IllegalArgumentException("test throw exception");
    }

    @RequestMapping(value = "/cache/{sid}")
    public ResponseEntity<SecKill> cache(@PathVariable long sid) throws UnsupportedEncodingException {
        SecKill secKill = secKillService.getSecKillById(sid);
        String version = secKill.getUpdateTime().toString();
        UriComponents uriComponents = UriComponentsBuilder.fromUriString("http://www.baidu.com?code={code}&status={status}").build();
        logger.info(URLEncoder.encode(uriComponents.expand("1", "ok").encode().toString(), "utf-8"));
        return ResponseEntity.ok().cacheControl(CacheControl.maxAge(30, TimeUnit.SECONDS)).eTag(version).body(secKill);
    }
}
