package com.controller.rest;

import com.entity.AddMember;
import com.entity.AjaxResponse;
import com.service.MemberProjectService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

/**
 *
 * Rest controller for the Members page.
 *
 * @author Laurentiu Marcut
 */
@RestController
public class MembersRestController {

    private static final Logger logger = Logger.getLogger(MembersRestController.class);

    @Autowired
    private MemberProjectService memberProjectService;

    /**
     *
     * Create member.
     *
     * @param project
     * @param addMember
     * @return response
     */
    @RequestMapping(value = "/members/createMember", method = RequestMethod.POST)
    public @ResponseBody AjaxResponse createMember(@CookieValue(value = "currentProject", defaultValue = "") String project,
                                             @RequestBody AddMember addMember) {
        AjaxResponse response = new AjaxResponse();

        try {
            this.memberProjectService.insert(project, addMember.getEmail(), addMember.getRole());
        } catch (Exception e) {
            logger.error("Error in inserting the member " + addMember.getEmail() + " in the project " + project +
                    " eith the role " + addMember.getEmail(), e);
            response.setState("KO");
            response.setMessage("Can not add the member.");
            return response;
        }

        response.setState("OK");
        response.setMessage("Member added.");
        return response;
    }

    /**
     *
     * Delete member.
     *
     * @param project
     * @param email
     * @return response
     */
    @RequestMapping(value = "/members/deleteMember", method = RequestMethod.POST)
    public @ResponseBody AjaxResponse deleteMember(@CookieValue(value = "currentProject", defaultValue = "") String project,
                                             @RequestBody String email) {
        AjaxResponse response = new AjaxResponse();

        try {
            this.memberProjectService.delete(project, email);
        } catch (Exception e) {
            logger.error("Error in deleteing the member " + email + " in the project " + project, e);
            response.setState("KO");
            response.setMessage("Can not remove the member.");
        }

        response.setState("OK");
        response.setMessage("Member removed.");
        return response;
    }

}
