package com.jsc.oscm.controller;

import com.alibaba.fastjson.JSON;
import com.jsc.oscm.entity.CloudServer;
import com.jsc.oscm.model.ReturnT;
import com.jsc.oscm.service.CrawlNodeService;
import com.jsc.oscm.service.CloudServerService;
import org.springframework.web.bind.annotation.*;

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

@RestController
public class CloudServerController {

    @Resource
    CloudServerService cloudServerService;

    @Resource
    CrawlNodeService crawlNodeService;

    @PostMapping("/host")
    public String addNode(@RequestBody CloudServer cloudNode) {
        ReturnT<CloudServer> returnT;
        CloudServer cHost = cloudServerService.addHost(cloudNode);
        if (cHost != null) {
            returnT = new ReturnT<>(200, "", cHost);
        } else {
            returnT = new ReturnT<>(500, "节点注册失败", null);
        }
        return JSON.toJSONString(returnT);
    }

    @GetMapping("/host/{page}/{size}")
    public String queryAllNodePageable(@PathVariable(value = "page") int page, @PathVariable(value = "size") int size) {
        ReturnT<List<CloudServer>> returnT;
        List<CloudServer> nodes = cloudServerService.queryAllHostPageable(page, size);
        returnT = new ReturnT<>(200, "", nodes);
        return JSON.toJSONString(returnT);
    }

    @GetMapping("/host/count")
    public String queryAllNodeCount() {
        ReturnT<Long> returnT;
        Long count = cloudServerService.queryAllHostCount();
        returnT = new ReturnT<>(200, "", count);
        return JSON.toJSONString(returnT);
    }

    @GetMapping("/host")
    public String queryAllNodes() {
        ReturnT<List<CloudServer>> returnT;
        List<CloudServer> nodes = cloudServerService.queryAllHosts();
        returnT = new ReturnT<>(200, "", nodes);
        return JSON.toJSONString(returnT);
    }

    @DeleteMapping("/host")
    public String delNode(@RequestBody List<Integer> nodeids) {
        ReturnT<String> returnT;
        //edit by pangq @2021/2/5 删除服务器时，删除底下节点
        if (!crawlNodeService.delCrawlNodesByHostIds(nodeids)) {
            return JSON.toJSONString(new ReturnT<>(500, "删除节点失败", ""));
        }

        if (cloudServerService.delHosts(nodeids)) {
            returnT = new ReturnT<>(200, "", "");
        } else {
            returnT = new ReturnT<>(500, "服务器删除失败", "");
        }
        return JSON.toJSONString(returnT);
    }

    @PutMapping("/host")
    public String updateNode(@RequestBody CloudServer cloudNode) {
        ReturnT<String> returnT;
        if (cloudServerService.updateHost(cloudNode)) {
            returnT = new ReturnT<>(200, "", "");
        } else {
            returnT = new ReturnT<>(500, "节点更新失败", "");
        }
        return JSON.toJSONString(returnT);
    }
}