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

import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.concurrent.atomic.AtomicBoolean;

import io.reactivex.schedulers.Schedulers;

import static junit.framework.Assert.assertTrue;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;

/**
 * InternetStatusTest
 * <pre>
 * </pre>
 *
 * @author 민효동
 * @version 1.0
 * @history 민효동   [2018. 9. 19.]   [최초 작성]
 * @since 2018. 9. 19.
 */
public class InternetStatusTest {

  @Before
  public void setUp() throws Exception {
  }

  @Test
  public void observe() {
    AtomicBoolean isChecked = new AtomicBoolean(false);

    InternetStatus.observe().subscribeOn(Schedulers.io())
      .subscribe(b -> {
        System.out.print("internet: " + b + '\n');
        isChecked.set(true);
      }, Throwable::printStackTrace);

    try {
      Thread.sleep(2000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }

    assertTrue(isChecked.get());
  }

  @Test
  public void check() {
    AtomicBoolean isChecked = new AtomicBoolean(false);

    InternetStatus.check().subscribeOn(Schedulers.io())
      .subscribe(b -> {
        System.out.print("internet: " + b + '\n');
        isChecked.set(true);
      }, Throwable::printStackTrace);

    try {
      Thread.sleep(2000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }

    assertTrue(isChecked.get());
  }

  @Test
  public void isConnected() throws IOException {
    Socket socket = mock(Socket.class);
    doThrow(new IOException()).when(socket).connect(new InetSocketAddress("host", 80), 1000);
    doThrow(new IOException()).when(socket).close();
    assertTrue(InternetStatus.isConnected(socket, "host", 80, 1000) == false);
  }
}