package kr.co.zumo.app.lifeplus.model;

import android.content.SharedPreferences;

import org.junit.Before;
import org.junit.Test;
import org.mockito.internal.verification.Times;

import java.util.HashSet;
import java.util.Set;

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.powermock.api.mockito.PowerMockito.when;

public class BaseSharedPreferencesTest {

  SharedPreferences preferences;
  BaseSharedPreferences baseSharedPreferences;
  SharedPreferences.Editor editor;

  @Before
  public void setUp() throws Exception {
    preferences = mock(SharedPreferences.class);
    editor = mock(SharedPreferences.Editor.class);
    when(preferences.edit()).thenReturn(editor);
    baseSharedPreferences = new BaseSharedPreferences(preferences);
  }

  @Test
  public void put() {
    when(editor.putString(any(), any())).thenReturn(editor);
    baseSharedPreferences.put("key", "value");

    verify(editor).putString(eq("key"), eq("value"));
    verify(editor).apply();
  }

  @Test
  public void put1() {
    when(editor.putBoolean(any(), eq(true))).thenReturn(editor);
    baseSharedPreferences.put("key", true);

    verify(editor).putBoolean(eq("key"), eq(true));
    verify(editor).apply();
  }

  @Test
  public void put2() {
    when(editor.putInt(any(), eq(Integer.MAX_VALUE))).thenReturn(editor);
    baseSharedPreferences.put("key", Integer.MAX_VALUE);

    verify(editor).putInt(eq("key"), eq(Integer.MAX_VALUE));
    verify(editor).apply();
  }

  @Test
  public void put3() {
    when(editor.putLong(any(), eq(Long.MAX_VALUE))).thenReturn(editor);
    baseSharedPreferences.put("key", Long.MAX_VALUE);

    verify(editor).putLong(eq("key"), eq(Long.MAX_VALUE));
    verify(editor).apply();
  }

  @Test
  public void put4() {
    when(editor.putFloat(any(), eq(Float.MAX_VALUE))).thenReturn(editor);
    baseSharedPreferences.put("key", Float.MAX_VALUE);

    verify(editor).putFloat(eq("key"), eq(Float.MAX_VALUE));
    verify(editor).apply();
  }

  @Test
  public void put5() {
    Set<String> stringSet = new HashSet<>();
    stringSet.add("A");
    stringSet.add("B");
    stringSet.add("C");
    when(editor.putStringSet(any(), eq(stringSet))).thenReturn(editor);

    baseSharedPreferences.put("key", stringSet);

    verify(editor).putStringSet(eq("key"), eq(stringSet));
    verify(editor).apply();
  }

  @Test
  public void remove() {
    when(editor.putString(any(), any())).thenReturn(editor);
    when(editor.remove(any())).thenReturn(editor);

    baseSharedPreferences.put("key", "value");

    verify(editor).putString(eq("key"), eq("value"));
    verify(editor).apply();

    baseSharedPreferences.remove("key");

    verify(editor).remove(eq("key"));
    verify(editor, new Times(2)).apply();
  }
}