package com.weavi.controller;

import com.weavi.entity.User;
import com.weavi.entity.Users;
import com.weavi.repository.UsersRepository;
import com.weavi.util.ResponseDTO;
import org.apache.commons.collections.IteratorUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

@Controller
public class UsersController {
    @Autowired
    private UsersRepository customerRepository;

    @RequestMapping(value = "/user", method = RequestMethod.GET)
    public String user() {
        return "user";
    }

    @ResponseBody
    @RequestMapping(value = "/user/list")
    public ResponseDTO<Users> list() {
        Iterable<Users> all = customerRepository.findAll();
        List<Users> list = IteratorUtils.toList(all.iterator());
        return new ResponseDTO<Users>(true, list.size(), list);
    }

    @ResponseBody
    @RequestMapping(value = "/user/add")
    public ResponseDTO<Users> add(Users user) {
        Users result = customerRepository.save(user);
        List<Users> list = new ArrayList<Users>();
        list.add(result);
       return new ResponseDTO<Users>(true, 1, list);
    }

    @ResponseBody
    @RequestMapping(value = "/user/save")
    public ResponseDTO<Users> save(@RequestParam("id") Long id, Users user) {
        user.setId(id);
        customerRepository.save(user);
        List<Users> list = new ArrayList<Users>();
        list.add(user);
        return new ResponseDTO<Users>(true, 1, list);
    }

    @ResponseBody
    @RequestMapping(value = "/user/delete")
    public ResponseDTO delete(@RequestParam("id") Long id) {
        customerRepository.delete(id);
        return new ResponseDTO<Users>(true, null, null);
    }

}
