package com.easy.monads.examples;

import com.easy.monads.Either;
import okhttp3.*;
import okhttp3.Request.Builder;

import java.io.IOException;

/**
 * Created by raja on 1/29/17.
 */
public class EitherExamples {
    public static void main(String[] args) {
        example1();
        example2();
        example3();
    }

    private static void example1() {
        Either.success("hello")
                .map(s -> s.toUpperCase())
                .map(s -> s + "!")
                .peek(System.out::println, System.out::println);
    }

    private static void example2() {
        Either.<Exception, String>error(new Exception("Don't Panic"))
                .map(s -> s.toUpperCase())
                .map(s -> s + "!")
                .peek(System.out::println, System.out::println);
    }

    private static void example3() {
        Either.<IOException, Builder>success(new Request.Builder())
                .map(b -> b.url("http://www.mocky.io/v2/589014230f00005312a3efd5"))
                .map(b -> b.header("Accept", "application/json"))
                .map(b -> b.build())
                .map(req -> new OkHttpClient().newCall(req))
                .flatMap(call -> execute(call))
                .peek(System.out::println, System.out::println)
                .map(res -> res.body())
                .flatMap(body -> string(body))
                .peek(System.out::println, System.out::println);
    }

    private static Either<IOException, Response> execute(Call call) {
        try {
            return Either.success(call.execute());
        } catch (IOException e) {
            return Either.error(e);
        }
    }

    private static Either<IOException, String> string(ResponseBody body) {
        try {
            return Either.success(body.string());
        } catch (IOException e) {
            return Either.error(e);
        }
    }
}

@@ -1068,25 +1068,29 @@
        .
-m
+flatM
 ap(b -%3E 
 b.build(
@@ -1085,16 +1085,15 @@
  -%3E 
-b.
 build(
+b
 ))%0A 
@@ -1415,32 +1415,295 @@
 rintln);%0A    %7D%0A%0A
+    private static Either%3CIOException, Request%3E build(Builder builder) %7B%0A        try %7B%0A            return Either.success(builder.build());%0A        %7D catch (Exception e) %7B%0A            return Either.error(new IOException(e.getLocalizedMessage()));%0A        %7D%0A    %7D%0A%0A
     private stat

enhance Either Monad example