package com.izouma.nineth.web;

import com.fasterxml.jackson.annotation.JsonView;
import com.izouma.nineth.domain.TestClass;
import com.izouma.nineth.dto.PageQuery;
import com.izouma.nineth.exception.BusinessException;
import com.izouma.nineth.repo.TestClassRepo;
import com.izouma.nineth.service.TestClassService;
import com.izouma.nineth.utils.excel.ExcelUtils;
import io.github.bucket4j.Bandwidth;
import io.github.bucket4j.Bucket;
import io.github.bucket4j.BucketConfiguration;
import io.github.bucket4j.Refill;
import io.github.bucket4j.distributed.proxy.ProxyManager;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.Duration;
import java.util.List;

@RestController
@RequestMapping("/testClass")
@AllArgsConstructor
@Slf4j
public class TestClassController extends BaseController {
    private TestClassService     testClassService;
    private TestClassRepo        testClassRepo;
    private ProxyManager<String> buckets;

    //@PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/save")
    public TestClass save() {
        long ts = System.currentTimeMillis();
        TestClass t = new TestClass("aaa");
        log.info("create testClass {}ms", System.currentTimeMillis() - ts);
        ts = System.currentTimeMillis();
        t = testClassRepo.save(t);
        log.info("save testClass {}ms", System.currentTimeMillis() - ts);
        return t;
    }

    @PostMapping("/save1")
    public void save1() {
        testClassRepo.nativeSave("aaa");
    }

    //@PreAuthorize("hasRole('ADMIN')")
    @GetMapping("/all")
    @JsonView(TestClass.View.Basic.class)
    public Page<TestClass> all(PageQuery pageQuery) {
        return testClassService.all(pageQuery);
    }

    @GetMapping("/get/{id}")
    @JsonView(TestClass.View.Basic.class)
    public TestClass get(@PathVariable Long id) {
        return testClassRepo.findById(id).orElseThrow(new BusinessException("无记录"));
    }

    @GetMapping("/excel")
    @ResponseBody
    public void excel(HttpServletResponse response, PageQuery pageQuery) throws IOException {
        List<TestClass> data = all(pageQuery).getContent();
        ExcelUtils.export(response, data);
    }

    @GetMapping("/test")
    public String test() {
        Bucket bucket = buckets.builder().build("test1", () -> (BucketConfiguration.builder()
                .addLimit(Bandwidth.classic(300, Refill.intervally(300, Duration.ofSeconds(30))))
                .build()));
        if (bucket.tryConsume(1)) {
            return "ok";
        } else {
            throw new BusinessException("rate limit");
        }
    }
}

