package com.insa.app.controller;

import com.insa.app.model.User;
import com.insa.app.model.Users;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;

import java.util.List;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;
import java.util.logging.Level;
import java.util.logging.Logger;

public class UserController {
    Users users;


    public UserController(User user) {
        if (user == null) {
            Logger.getAnonymousLogger().log(Level.INFO, "No saved identity, creating new users");
            int rnd = ThreadLocalRandom.current().nextInt(0, 1000000 + 1);
            UUID id = UUID.randomUUID();
            users = new Users("User" + rnd, id);
        }
        else {
            users = new Users(user.getName(), user.getId());
        }
    }

    public void setMyIp(String ip) {
        users.setMyIp(ip);
    }

    public User getMe() {
        return users.getMe();
    }

    public ObservableList<User> getUserList() {
        return users.getOthers();
    }

    public void addUser(User user) {
        users.replaceOrInsert(user);
        users.setUserConnected(user);
    }

    public User[] getAllUsersList() {
       ObservableList<User> allUsers =  FXCollections.observableArrayList(users.getOthers());
       allUsers.add(users.getMe());
       return (User[]) allUsers.toArray();
    }

    public void deleteUser(User user) {
        users.setUserDisconnected(user);
    }

    public User getUserById(UUID id) throws RuntimeException {
        return users.getUserById(id);
    }

    public User getUserByIp(String ip) throws RuntimeException {
        return users.getUserByIp(ip);
    }

    public void replaceOrInsert(User user) {
        users.replaceOrInsert(user);
    }

    public String getMyUserName() {
        return users.getMyUserName();
    }


    public void setUserName(String name) {
        users.setUserName(name);
    }

    public List<User> getOtherUsers() {
        return users.getOthers();
    }

    public boolean isConnected(User user) {
        return users.isConnected(user);
    }

}
