package br.com.bloder.blormlib;

import android.view.View;

import java.util.ArrayList;
import java.util.List;

import br.com.bloder.blormlib.validation.Action;
import br.com.bloder.blormlib.validation.Validate;
import br.com.bloder.blormlib.validation.Validation;

/**
 * Created by bloder on 05/06/16.
 */
public class Blorm {

  public static class Builder {

    private List<Validate> validations;
    private View field;
    private Action onSuccess;

    public Builder() {
      validations = new ArrayList<>();
    }

    public Builder onSuccess(Action action) {
      this.onSuccess = action;
      return this;
    }

    public Builder field(View field) {
      this.field = field;
      return this;
    }

    public Builder is(Validate validation) {
      this.validations.add(validation);
      return this;
    }

    public Builder is(Validation validation) {
      validation.field = this.field;
      this.validations.add(validation.validate());
      return this;
    }

    public Builder is(String errorMessgae, Validation validation) {
      validation.field = this.field;
      validation.errorMessage = errorMessgae;
      this.validations.add(validation.validate());
      return this;
    }

    public void submitOn(View submittedItem) {
      submittedItem.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
          new Blorm(validations, onSuccess).onSubmitted();
        }
      });
    }
  }

  private List<Validate> validations;
  private Action onSuccess;
  private Boolean allValidationsPassed = true;
  
  public Blorm(List<Validate> validations, Action onSuccess) {
    this.validations = validations;
    this.onSuccess = onSuccess;
  }

  private void onSubmitted() {
    for(Validate validate : validations) {
      if(!validate.validate()) {
        allValidationsPassed = false;
        validate.onError();
      }
    }
    if(allValidationsPassed) {
      this.onSuccess.call();
    }
  }
}

@@ -449,16 +449,44 @@
 Success;
+%0A    private Action onError;
 %0A%0A    pu
@@ -643,32 +643,131 @@
 rn this;%0A    %7D%0A%0A
+    public Builder onError(Action action) %7B%0A      this.onError = action;%0A      return this;%0A    %7D%0A%0A
     public Build
@@ -1554,16 +1554,25 @@
 nSuccess
+, onError
 ).onSubm
@@ -1677,16 +1677,42 @@
 uccess;%0A
+  private Action onError;%0A
   privat
@@ -1812,16 +1812,32 @@
 nSuccess
+, Action onError
 ) %7B%0A    
@@ -1900,16 +1900,44 @@
 uccess;%0A
+    this.onError = onError;%0A
   %7D%0A%0A  p
@@ -2147,16 +2147,37 @@
 nsPassed
+ && onSuccess != null
 ) %7B%0A    
@@ -2197,24 +2197,109 @@
 ess.call();%0A
+    %7D else if(!allValidationsPassed && onError != null) %7B%0A      this.onError.call();%0A
     %7D%0A  %7D%0A%7D%0A

Add onError function logic in blorm class