/*
 * 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.Login;
import com.justjournal.model.Friend;
import com.justjournal.model.User;
import com.justjournal.repository.FriendsRepository;
import com.justjournal.repository.UserRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;

/**
 * Manage Friends
 *
 * @author Lucas Holt
 */
@Slf4j
@RestController
@RequestMapping("/api/friend")
public class FriendController {

    private final UserRepository userRepository;

    private final FriendsRepository friendsDao;

    @Autowired
    public FriendController(final UserRepository userRepository, final FriendsRepository friendsDao) {
        this.userRepository = userRepository;
        this.friendsDao = friendsDao;
    }

    // TODO: refactor to return user objects?


    @RequestMapping(value = "{username}/friendswith/{other}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public ResponseEntity<Boolean> areWeFriends(@PathVariable("username") String username, @PathVariable("other") String otherUsername) {
        try {
            User user = userRepository.findByUsername(username);
            if (user == null)
                return new ResponseEntity<>(HttpStatus.NOT_FOUND);
            
            for (Friend friend : user.getFriends()) {

                if (otherUsername.equalsIgnoreCase(friend.getFriend().getUsername()))
                    return ResponseEntity.ok(true);
            }
            return ResponseEntity.ok(false);
        } catch (final Exception e) {
            return ResponseEntity.badRequest().body(false);
        }
    }

    /**
     * @param username       username
     * @param response http response
     * @return List of usernames as strings
     */
    @Cacheable(value = "friends", key = "username")
    @RequestMapping(value = "{username}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Collection<User> getByUsername(@PathVariable("username") String username, HttpServletResponse response) {
        try {
            ArrayList<User> friends = new ArrayList<User>();

            User user = userRepository.findByUsername(username);
            for (Friend friend : user.getFriends()) {
                friends.add(friend.getFriend());
            }
            return friends;
        } catch (final Exception e) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return null;
        }
    }

    @CacheEvict(value = "friends", key = "friend")
    @RequestMapping(value="{friend}", method = RequestMethod.PUT, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Map<String, String> put(@PathVariable("friend") String friend, HttpSession session, HttpServletResponse response) {
        if (!Login.isAuthenticated(session)) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return java.util.Collections.singletonMap("error", "The login timed out or is invalid.");
        }

        try {
            final User friendUser = userRepository.findByUsername(friend);
            final User owner = userRepository.findOne(Login.currentLoginId(session));

            if (friendUser == null)
                return java.util.Collections.singletonMap("error", "Could not find friend's username");

            if (owner == null)
                return java.util.Collections.singletonMap("error", "Could not find logged in user account.");

            final Friend f = new Friend();
            f.setFriend(friendUser);
            f.setUser(owner);
            f.setPk(owner.getId());
            if (friendsDao.save(f) != null)
                return java.util.Collections.singletonMap("status", "success");

            return java.util.Collections.singletonMap("error", "Unable to add friend");
        } catch (final Exception e) {
            log.error(e.getMessage());
            return java.util.Collections.singletonMap("error", "Could not find friend's username");
        }

    }

    // TODO: api makes it hard to selectively delete cache entries
    @CacheEvict(value = "friends", allEntries = true)
    @RequestMapping(method = RequestMethod.DELETE)
    @ResponseBody
    public
    Map<String, String> delete(@RequestBody Friend friend, HttpSession session, HttpServletResponse response) throws Exception {


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

        try {
            final User user = userRepository.findOne(Login.currentLoginId(session));
            friend.setUser(user);

            friendsDao.delete(friend);
            return java.util.Collections.singletonMap("status", "success");
        } catch (final Exception e) {
            log.error(e.getMessage(), e);
        }

        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return java.util.Collections.singletonMap("error", "Error deleting friend");
    }
}

@@ -5905,75 +5905,12 @@
   %7D%0A
-%0A
     
-// TODO: api makes it hard to selectively delete cache entries
 %0A   
@@ -6009,16 +6009,34 @@
 d.DELETE
+, value=%22%7Bfriend%7D%22
 )%0A    @R
@@ -6094,26 +6094,37 @@
 te(@
-RequestBody Friend
+PathVariable(%22friend%22) String
  fri
@@ -6434,32 +6434,107 @@
 %0A%0A        try %7B%0A
+            final User friendUser = userRepository.findByUsername(friend);%0A
             fina
@@ -6598,24 +6598,25 @@
 (session));%0A
+%0A
             
@@ -6620,30 +6620,110 @@
    f
-riend.setUser(user);%0A%0A
+inal Friend f = friendsDao.findOneByUserAndFriend(user, friendUser);%0A            if (f != null) %7B%0A    
     
@@ -6749,24 +6749,23 @@
 delete(f
-riend);%0A
+);%0A    
         
@@ -6828,24 +6828,227 @@
 %22success%22);%0A
+            %7D else %7B%0A                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);%0A                   return java.util.Collections.singletonMap(%22error%22, %22Error deleting friend%22);%0A            %7D%0A
         %7D ca
@@ -7172,35 +7172,45 @@
 Response.SC_
-BAD_REQUEST
+INTERNAL_SERVER_ERROR
 );%0A        r

change delete interface