package com.dtok.api.controller;

import com.dtok.entity.AppInfo;
import com.dtok.framework.exception.BizExceptionEnum;
import com.dtok.framework.response.ResponseData;
import com.dtok.repository.AppInfoRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.xml.ws.Action;
import java.util.Objects;

@RestController
@RequestMapping("/appInfo")
public class AppInfoController {

    @Autowired
    AppInfoRepository appInfoRepository;

    @GetMapping("/search")
    public ResponseData search(@RequestParam("name") String name) {
        if (StringUtils.hasLength(name)) {
            return ResponseData.success(appInfoRepository.findAllByNameLike(name));
        } else {
            return ResponseData.success(appInfoRepository.findAll());
        }
    }

    @PostMapping("/add")
    public ResponseData add(AppInfo appInfo) {
        if (Objects.isNull(appInfo)) {
            throw new NullPointerException(BizExceptionEnum.SERVER_ERROR.getMessage());
        }
        if (!StringUtils.hasLength(appInfo.getPackageName())) {
            throw new NullPointerException(BizExceptionEnum.SERVER_ERROR.getMessage());
        }

        appInfoRepository.save(appInfo);
        return ResponseData.success("添加成功");
    }

    @PostMapping("/update")
    public ResponseData update(AppInfo appInfo) {
        if (Objects.isNull(appInfo)) {
            throw new NullPointerException(BizExceptionEnum.SERVER_ERROR.getMessage());
        }
        if (!StringUtils.hasLength(appInfo.getPackageName())) {
            throw new NullPointerException(BizExceptionEnum.SERVER_ERROR.getMessage());
        }
        appInfoRepository.save(appInfo);
        return ResponseData.success("修改成功");
    }

    @PostMapping("/delete/{id}")
    public ResponseData delete(@PathVariable String id) {
        if (Objects.isNull(id)) {
            throw new NullPointerException(BizExceptionEnum.SERVER_ERROR.getMessage());
        }
        appInfoRepository.deleteById(id);
        return ResponseData.success("修改成功");
    }

}
