package com.sdut.labex.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sdut.labex.Factory.BorrowInfoFactory;
import com.sdut.labex.entity.BorrowInfo;
import com.sdut.labex.service.BorrowInfoService;
import com.sdut.labex.utils.ResVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * File: BorrowInfoController
 * Created: 2023/6/12
 * Author: springforest
 * Description:
 */
@RestController
@CrossOrigin
@Slf4j
public class BorrowInfoController {

    @Resource
    private BorrowInfoService borrowInfoService;

    @PostMapping("/borrowInfo")
    public ResVo addBorrowInfo(@RequestBody JSONObject jsonObject) {
        JSONArray timeList = jsonObject.getJSONArray("time");
        BorrowInfo borrowInfo = BorrowInfoFactory.createBorrowInfo(jsonObject);
        List<String> list = new ArrayList<>();
        for (Object item : timeList) {
            list.add(item.toString());
        }
        return borrowInfoService.borrow(list, borrowInfo);
    }

    @PostMapping("/borrowInfo/notBorrowedYet")
    public ResVo notBorrowedYet(@RequestBody JSONObject jsonObject) {
        JSONArray jsonArray = jsonObject.getJSONArray("time");

        String date = jsonObject.getString("date");

        List<String> timeList = new ArrayList<>();
        for (Object item : jsonArray) {
            timeList.add(item.toString());
        }

        return borrowInfoService.notBorrowedYet(timeList, date);
    }

    @DeleteMapping("/borrowInfo/{id}")
    public ResVo deleteBorrowInfoById(@PathVariable("id") Integer id) {
        return borrowInfoService.deleteBorrowInfoById(id);
    }

    @PostMapping("/borrowInfo/{pageNum}/{pageSize}")
    public ResVo getBorrowInfo(@RequestBody JSONObject jsonObject,
                               @PathVariable("pageNum") int pageNum,
                               @PathVariable("pageSize") int pageSize) {
        BorrowInfo borrowInfo = BorrowInfoFactory.createBorrowInfo(jsonObject);
        if (borrowInfo != null) {
            borrowInfo.setTime(jsonObject.getString("time"));
        }
        return borrowInfoService.getBorrowInfo(borrowInfo, pageNum, pageSize);
    }

}
