package com.atlassian.stash.internal.user;

import com.atlassian.bitbucket.annotation.Dao;
import com.atlassian.bitbucket.annotation.DataSet;
import com.atlassian.stash.internal.AbstractDaoTest;
import com.atlassian.stash.internal.ApplicationConstants;
import com.atlassian.stash.internal.DataSets;
import com.atlassian.stash.internal.setting.InternalSharedLob;
import org.junit.Test;

@DataSet({DataSets.USERS, DataSets.SHARED_LOBS, DataSets.USER_SETTINGS})
public class HibernateUserSettingsDaoTest extends AbstractDaoTest {

    private static final String NEW_DATA = "\"newKey\"=\"newValue\"}";

    @Dao
    private HibernateUserSettingsDao dao;
    @Dao(HibernateStashUserDao.class)
    private StashUserDao userDao;

    @Test
    public void testCreate() {
        InternalApplicationUser user = userDao.loadById(1);

        InternalUserSettings userSettings = new InternalUserSettings.Builder()
                .user(user)
                .settings(new InternalSharedLob.Builder().data(NEW_DATA).build())
                .build();

        InternalUserSettings created = dao.create(userSettings);
        assertNotNull(created.getId());

        flush();
        evict(created, created.getId());

        assertEquals(userSettings.getId(), created.getId());

        InternalUserSettings loadedSettings = dao.getById(created.getId());
        assertEquals(NEW_DATA, loadedSettings.getSettings().getData());
    }

    @Test
    public void testCreateWithNewSettings() {
        InternalApplicationUser userOne = userDao.loadById(1);

        InternalSharedLob lob = new InternalSharedLob.Builder().data(NEW_DATA).build();
        InternalUserSettings userSettings = new InternalUserSettings.Builder()
                .user(userOne)
                .settings(lob)
                .build();

        InternalUserSettings created = dao.create(userSettings);
        assertNotNull(created.getId());
        assertNotNull(lob.getId());

        flush();
        evict(created, created.getId());

        assertEquals(userSettings.getId(), created.getId());
        assertNotEquals(ApplicationConstants.UNSAVED_ENTITY, created.getSettings().getId());

        InternalUserSettings loaded = dao.getById(created.getId());
        assertEquals(NEW_DATA, loaded.getSettings().getData());
    }

    @Test
    public void testFindUserId() {
        InternalApplicationUser one = userDao.loadById(1);
        InternalApplicationUser two = userDao.loadById(2);

        assertNull(dao.getById(one.getId())); // No user settings for this user
        assertEquals("{\"key\"=\"value\"}", dao.getById(two.getId()).getSettings().getData()); // Settings with Data
    }
}
