package easydo.technology.core.controllers;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import easydo.technology.core.SpringRequestUser;
import easydo.technology.core.ZeroCoreSpringController;
import zmo.technology.lite.core.ZeroException;
import zmo.technology.lite.core.ZeroRequestGuider;

@Controller
@RequestMapping(ZeroSpringUserController.ZUSER_PREFIX)
public class ZeroSpringUserController extends ZeroCoreSpringController {

    public static final String ZUSER_PREFIX = "zuser";

    public ZeroSpringUserController() {
        super(ZUSER_PREFIX);
    }

    @Autowired
    private DataSource dataSource;

    @Override
    protected String handlerNameConstructor(ZeroRequestGuider guider) throws Exception {
        if (guider.getPaths().size() != 1)
            throw new ZeroException(404, "no handlers");
        return guider.getPaths().get(0);
    }

    @RequestMapping(GENERAL_HANDLER_PATH)
    public void general(HttpServletRequest request, HttpServletResponse response) throws Exception {
        proxyHandler(dataSource, request, response);
    }

    public void projects(ZeroRequestGuider guider) throws Exception {
        SpringRequestUser user = guider.fetchJSONStaging(REQUEST_USER, SpringRequestUser.class);
        if (user.getProjectInfos().isEmpty())
            throw new ZeroException("access denied");
        guider.write(success(user.getProjectInfos()));
    }
    
    public void infos(ZeroRequestGuider guider) throws Exception {
        SpringRequestUser user = guider.fetchJSONStaging(REQUEST_USER, SpringRequestUser.class);
        if (user.getProjectInfos().isEmpty())
            throw new ZeroException("access denied"); 
        List<SpringRequestUser> users = new ArrayList<>();
        users.add(user);
        guider.write(success(users));
    }
}
