package com.alterdekim.game.service;

import com.alterdekim.game.entity.Relationship;
import com.alterdekim.game.entity.User;
import com.alterdekim.game.repository.RelationshipRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class RelationshipService {

    @Autowired
    private RelationshipRepository repository;

    public void save(Relationship relationship) {
        this.repository.save(relationship);
    }

    public Boolean isFriends(Integer userId, Integer userId1) {
        return this.repository.findRelation(userId, userId1, Relationship.FriendshipStatus.Friendship).isPresent();
    }

    public Optional<Relationship> isRequestSent(Integer userId, Integer userId1) {
        return this.repository.findRelation(userId, userId1, Relationship.FriendshipStatus.Request);
    }

    public void deleteRequest(Long id) {
        this.repository.deleteById(id);
    }

    public void acceptRequest(Long id) {
        this.repository.acceptRequestById(id);
    }

    public void sendRequest(Integer sender, Integer receiver) {
        if( this.isFriends(sender, receiver) ) return;
        if( this.isRequestSent(sender, receiver).isPresent() ) {
            Relationship r = this.isRequestSent(sender, receiver).get();
            if( r.getRecepientId().longValue() != sender.longValue() ) return;
            this.acceptRequest(r.getId());
            return;
        }
        this.repository.save(new Relationship(null, sender, receiver, Relationship.FriendshipStatus.Request));
    }

    public void deleteFriendshipByUserIds(Integer userId1, Integer userId2) {
        this.repository.deleteFriendshipByUserIds(userId1, userId2);
    }

    public List<User> getFriendsOfUser(Integer userId) {
        return this.repository.findFriendsOfUserById(userId);
    }

    public List<User> getRequestsOfUser(Integer userId) {
        return this.repository.findRequestsOfUserById(userId);
    }

    public void acceptFriendshipWithUsers(Integer userId, List<Integer> users) {
        this.repository.acceptFriendshipWithUsers(userId, users);
    }

    public void denyFriendshipsWithUsers(Integer userId, List<Integer> users) {
        this.repository.denyFriendshipsWithUsers(userId, users);
    }
}
