package com.controller.rest;

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

import javax.servlet.http.HttpServletRequest;

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

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

    @Autowired
    private TaskService taskService;

    @Autowired
    private MemberProjectService memberProjectService;

    /**
     * Create a task.
     *
     * @param project
     * @param task
     * @param request
     * @return response
     */
    @RequestMapping(value = "/backlog/createTask", method = RequestMethod.POST)
    public @ResponseBody AjaxResponse createTask(@CookieValue(value = "currentProject", defaultValue = "") String project,
                                         @RequestBody Task task, HttpServletRequest request) {
        AjaxResponse response = new AjaxResponse();
        String member = request.getUserPrincipal().getName();

        if (StringUtils.isEmpty(task.getState())) {
            task.setState("To do");
        }

        try {
            Member createdBy = this.memberProjectService.select(project, member);
            task.setProject(project);
            task.setCreatedBy(createdBy.getFirstName() + " " + createdBy.getLastName());
            this.taskService.insert(task);

            response.setState("OK");
            response.setMessage("Task created.");
        } catch (Exception e) {
            logger.error("Can not create the task. ", e);
            response.setState("KO");
            response.setMessage("Can not create the task.");
        }

        return response;
    }

    /**
     *
     * Delete a task.
     *
     * @param project
     * @param task
     * @return response
     */
    @RequestMapping(value = "/backlog/deleteTask", method = RequestMethod.POST)
    public @ResponseBody AjaxResponse deleteTask(@CookieValue(value = "currentProject", defaultValue = "") String project,
                                                 @RequestBody DeleteTask task) {
        AjaxResponse ajaxResponse = new AjaxResponse();

        try {
            this.taskService.delete(project, task.getId(), task.getPriority());
            ajaxResponse.setState("OK");
            ajaxResponse.setMessage("Task deleted.");
        } catch (Exception e) {
            logger.error("Can not delete the task. ", e);
            ajaxResponse.setState("KO");
            ajaxResponse.setMessage("Can not delete the task.");
        }

        return ajaxResponse;
    }

    /**
     *
     * Update task priority.
     *
     * @param project
     * @param task
     * @return response
     */
    @RequestMapping(value = "/backlog/updateTaskPriority", method = RequestMethod.POST)
    public @ResponseBody AjaxResponse updateTaskPriority(@CookieValue(value = "currentProject", defaultValue = "") String project,
                                                         @RequestBody UpdateTask task) {
        AjaxResponse ajaxResponse = new AjaxResponse();

        try {
            this.taskService.updatePriority(project, task.getId(), task.getPreviousPriority(), task.getCurrentPriority());
            ajaxResponse.setState("OK");
            ajaxResponse.setMessage("Priority updated.");
        } catch (Exception e) {
            logger.error("Can not update the priority. ", e);
            ajaxResponse.setState("KO");
            ajaxResponse.setMessage("Can not update the priority.");
        }

        return ajaxResponse;
    }

    /**
     *
     * Update task cost.
     *
     * @param task
     * @return response
     */
    @RequestMapping(value = "/backlog/updateTaskCost", method = RequestMethod.POST)
    public @ResponseBody AjaxResponse updateTaskCost(@RequestBody Task task) {
        AjaxResponse ajaxResponse = new AjaxResponse();

        try {
            this.taskService.updatePoints(task.getId(), task.getPoints());
            ajaxResponse.setState("OK");
            ajaxResponse.setMessage("Cost updated.");
        } catch (Exception e) {
            logger.error("Can not update the cost. ", e);
            ajaxResponse.setState("KO");
            ajaxResponse.setMessage("Can not update the cost.");
        }

        return ajaxResponse;
    }

    /**
     *
     * Update task assigned to.
     *
     * @param task
     * @return response
     */
    @RequestMapping(value = "/backlog/updateTaskAssignTo", method = RequestMethod.POST)
    public @ResponseBody AjaxResponse updateTaskAssignTo(@RequestBody Task task) {
        AjaxResponse ajaxResponse = new AjaxResponse();

        try {
            this.taskService.updateAssignedTo(task.getId(), task.getAssignedTo());
            ajaxResponse.setState("OK");
            ajaxResponse.setMessage("Member assigned to the task.");
        } catch (Exception e) {
            logger.error("Can not assign the member to the task. ", e);
            ajaxResponse.setState("KO");
            ajaxResponse.setMessage("Can not assign the member to the task.");
        }

        return ajaxResponse;
    }

    /**
     *
     * Update task state.
     *
     * @param task
     * @return response
     */
    @RequestMapping(value = "/backlog/updateTaskState", method = RequestMethod.POST)
    public @ResponseBody AjaxResponse updateTaskState(@RequestBody Task task) {
        AjaxResponse ajaxResponse = new AjaxResponse();

        try {
            this.taskService.updateState(task.getId(), task.getState());
            ajaxResponse.setState("OK");
            ajaxResponse.setMessage("State updated.");
        } catch (Exception e) {
            logger.error("Error in updating the task state. ", e);
            ajaxResponse.setState("KO");
            ajaxResponse.setMessage("Can not update the state of the task.");
        }

        return ajaxResponse;
    }

    /**
     *
     * Add task tag.
     *
     * @param task
     * @return response
     */
    @RequestMapping(value = "/backlog/addTaskTag", method = RequestMethod.POST)
    public @ResponseBody AjaxResponse addTaskTag(@RequestBody Task task) {
        AjaxResponse ajaxResponse = new AjaxResponse();
        String tag = task.getTags().get(0);

        try {
            this.taskService.insertTag(task.getId(), tag);
            ajaxResponse.setState("OK");
            ajaxResponse.setMessage("Tag added.");
        } catch (Exception e) {
            logger.error("Can not add the tag. ", e);
            ajaxResponse.setState("KO");
            ajaxResponse.setMessage("Can not add the tag.");
        }

        return ajaxResponse;
    }

    /**
     *
     * Delete task tag.
     *
     * @param task
     * @return response
     */
    @RequestMapping(value = "/backlog/deleteTaskTag", method = RequestMethod.POST)
    public @ResponseBody AjaxResponse deleteTaskTag(@RequestBody Task task) {
        AjaxResponse ajaxResponse = new AjaxResponse();
        String tag = task.getTags().get(0);

        try {
            this.taskService.deleteTag(task.getId(), tag);
            ajaxResponse.setState("OK");
            ajaxResponse.setMessage("Tag deleted.");
        } catch (Exception e) {
            logger.error("Can not delete the tag. ", e);
            ajaxResponse.setState("KO");
            ajaxResponse.setMessage("Can not delete the tag.");
        }

        return ajaxResponse;
    }

}
