/*
 * Copyright (c) 2013 Lucas Holt
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

package com.justjournal.ctl.api;

import com.justjournal.WebLogin;
import com.justjournal.db.*;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Collections;
import java.util.Map;

/**
 * @author Lucas Holt
 */
@Controller
@RequestMapping("/api/entry")
final public class EntryController {
    private static final Logger log = Logger.getLogger(EntryController.class);

    /**
     * Creates a new entry resource
     * @param entry
     * @param session
     * @param response
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, produces = "application/json")
    public
    @ResponseBody
    Map<String, String> post(@RequestBody EntryTo entry, HttpSession session, HttpServletResponse response) {

        if (!WebLogin.isAuthenticated(session)) {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            return java.util.Collections.singletonMap("error", "The login timed out or is invalid.");
        }
        // TODO: validate
        boolean result = EntryDAO.add(entry);

        if (!result) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return java.util.Collections.singletonMap("error", "Could not add the entry.");
        }
        return java.util.Collections.singletonMap("id", Integer.toString(entry.getId()));
    }

    /**
     * PUT generally allows for add or edit in REST.
     * @param entry
     * @param session
     * @param response
     * @return
     */
    @RequestMapping(method = RequestMethod.PUT, produces = "application/json")
    public
    @ResponseBody
    Map<String, String> put(@RequestBody EntryTo entry, HttpSession session, HttpServletResponse response) {

        if (!WebLogin.isAuthenticated(session)) {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            return java.util.Collections.singletonMap("error", "The login timed out or is invalid.");
        }
        // TODO: validate
        boolean result;
        EntryTo entryTo = EntryDAO.viewSingle(entry.getId(), WebLogin.currentLoginId(session));
        if (entryTo != null && entryTo.getId() > 0)
            result = EntryDAO.update(entry);
        else
            result = EntryDAO.add(entry);

        if (!result) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return java.util.Collections.singletonMap("error", "Could not add/edit entry.");
        }
        return java.util.Collections.singletonMap("id", Integer.toString(entry.getId()));
    }

    @RequestMapping(method = RequestMethod.DELETE)
    public
    @ResponseBody
    Map<String, String> delete(@RequestBody int entryId, HttpSession session, HttpServletResponse response) throws Exception {

        if (!WebLogin.isAuthenticated(session)) {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            return java.util.Collections.singletonMap("error", "The login timed out or is invalid.");
        }

        if (entryId < 1)
            return Collections.singletonMap("error", "The entry id was invalid.");

        try {
            boolean result2;
            boolean result = EntryDAO.delete(entryId, WebLogin.currentLoginId(session));

            if (!result) {
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                return java.util.Collections.singletonMap("error", "Could not delete entry.");
            }

            result2 = CommentDao.deleteByEntry(entryId);
            if (!result2) {
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                return java.util.Collections.singletonMap("error", "Could not delete comments associated with entry.");
            }

            return java.util.Collections.singletonMap("id", Integer.toString(entryId));
        } catch (Exception e) {
            log.error(e.getMessage());
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return java.util.Collections.singletonMap("error", "Could not delete the comment.");
        }
    }
}

@@ -1574,205 +1574,9 @@
 ion.
-RequestBody;%0Aimport org.springframework.web.bind.annotation.RequestMapping;%0Aimport org.springframework.web.bind.annotation.RequestMethod;%0Aimport org.springframework.web.bind.annotation.ResponseBody
+*
 ;%0A%0Ai
@@ -1660,16 +1660,45 @@
 ession;%0A
+import java.util.Collection;%0A
 import j
@@ -1927,24 +1927,523 @@
 er.class);%0A%0A
+    /**%0A     * Get an individual entry%0A     *%0A     * @param id entry id%0A     * @return entry%0A     */%0A    @RequestMapping(%22/api/entry/%7Bid%7D%22)%0A    @ResponseBody%0A    public EntryTo getById(@PathVariable Integer id) %7B%0A        return EntryDAO.viewSinglePublic(id);%0A    %7D%0A%0A    @RequestMapping(method = RequestMethod.GET, produces = %22application/json%22)%0A    public%0A    @ResponseBody%0A    Collection%3CEntryTo%3E getEntries(@RequestParam String username) %7B%0A        return EntryDAO.viewAll(username, false);%0A    %7D%0A%0A
     /**%0A    
@@ -2474,16 +2474,23 @@
 esource%0A
+     *%0A
      * @
@@ -3441,16 +3441,23 @@
 n REST.%0A
+     *%0A
      * @

allow a single entry to be selected or all entries for a user