package com.zulip.android.networking;

import org.apache.http.HttpStatus;
import org.apache.http.client.HttpResponseException;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.util.Log;
import android.widget.Toast;

import com.zulip.android.activities.DevAuthActivity;
import com.zulip.android.activities.LoginActivity;
import com.zulip.android.util.ZLog;
import com.zulip.android.ZulipApp;

public class AsyncLogin extends ZulipAsyncPushTask {
    public static final String UNREGISTERED = "unregistered";
    public static final String DISABLED = "disabled";

    Activity activity;
    boolean userDefinitelyInvalid = false;
    boolean devServer = true; //If this is a DevAuthBackend server!

    public AsyncLogin(Activity activity, String username, String password, boolean devServer) {
        super(ZulipApp.get());
        this.activity = activity;
        if (username.contains("@")) {
            // @-less usernames are used as indicating special cases, for
            // example in OAuth2 authentication
            this.app.setEmail(username);
        }
        this.setProperty("username", username);
        if (!devServer) {
            this.setProperty("password", password);
            this.devServer = false;
        }
    }

    public final void execute() {
        if (devServer) execute("POST", "v1/dev_fetch_api_key");
        else execute("POST", "v1/fetch_api_key");
    }

    @Override
    protected void onPostExecute(String result) {
        if (result != null) {
            try {
                JSONObject obj = new JSONObject(result);

                if (obj.getString("result").equals("success")) {
                    this.app.setLoggedInApiKey(obj.getString("api_key"));
                        if (devServer) ((DevAuthActivity) activity).openHome();
                        else ((LoginActivity) activity).openHome();
                    callback.onTaskComplete(result, obj);

                    return;
                }
            } catch (JSONException e) {
                ZLog.logException(e);
            }
        }
        Toast.makeText(activity, "Unknown error", Toast.LENGTH_LONG).show();
        Log.wtf("login", "We shouldn't have gotten this far.");
    }

    @Override
    protected void handleHTTPError(final HttpResponseException e) {
        if (e.getStatusCode() == HttpStatus.SC_FORBIDDEN) {
            String message = "Unknown authentication error.";
            try {
                JSONObject obj = new JSONObject(e.getMessage());
                String reason = obj.getString("reason");
                message = obj.getString("msg");
                /*
                 * If you're disabled or unregistered, your credentials were
                 * valid but you are not able to use the service.
                 * 
                 * This is useful in the context of Google Apps login where we
                 * want to differentiate between "bad credentials" and
                 * "not permitted by policy". So, an authentication vs.
                 * authorization thing.
                 */
                userDefinitelyInvalid = reason.equals(AsyncLogin.DISABLED)
                        || reason.equals(AsyncLogin.UNREGISTERED);
            } catch (JSONException e1) {
                ZLog.logException(e1);
            }
            final String finalMessage = message;
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(activity, finalMessage, Toast.LENGTH_LONG)
                            .show();
                }
            });
            this.cancel(true);
        } else {
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(activity, "Network error", Toast.LENGTH_LONG)
                            .show();
                }
            });
            // supermethod invokes cancel for us
            super.handleHTTPError(e);
        }
    }
}

@@ -36,96 +36,8 @@
 g;%0A%0A
-import org.apache.http.HttpStatus;%0Aimport org.apache.http.client.HttpResponseException;%0A
 impo
@@ -406,29 +406,30 @@
 Task %7B%0A    p
-ublic
+rivate
  static fina
@@ -473,21 +473,22 @@
 %22;%0A    p
-ublic
+rivate
  static 
@@ -551,51 +551,8 @@
 ty;%0A
-    boolean userDefinitelyInvalid = false;%0A
     
@@ -614,16 +614,102 @@
  server!
+%0A    private LoginActivity context;%0A    private boolean userDefinitelyInvalid = false;
 %0A%0A    pu
@@ -1733,28 +1733,24 @@
             
-    
 if (devServe
@@ -1785,36 +1785,32 @@
 ty).openHome();%0A
-    
                 
@@ -1915,17 +1915,16 @@
 , obj);%0A
-%0A
         
@@ -2248,121 +2248,72 @@
 oid 
-handleHTTPError(final HttpResponseException e) %7B%0A        if (e.getStatusCode() == HttpStatus.SC_FORBIDDEN) %7B%0A    
+onCancelled(String result) %7B%0A        super.onCancelled(result);%0A
     
@@ -2366,20 +2366,16 @@
 rror.%22;%0A
-    
         
@@ -2384,36 +2384,32 @@
 y %7B%0A            
-    
 JSONObject obj =
@@ -2428,740 +2428,61 @@
 ect(
-e.getMessage());%0A                String reason = obj.getString(%22reason%22);%0A                message = obj.getString(%22msg%22);%0A                /*%0A                 * If you're disabled or unregistered, your credentials were%0A                 * valid but you are not able to use the service.%0A                 * %0A                 * This is useful in the context of Google Apps login where we%0A                 * want to differentiate between %22bad credentials%22 and%0A                 * %22not permitted by policy%22. So, an authentication vs.%0A                 * authorization thing.%0A                 */%0A                userDefinitelyInvalid = reason.equals(AsyncLogin.DISABLED)%0A                        %7C%7C reason.equals(AsyncLogin.UNREGISTERED);%0A    
+result);%0A            message = obj.getString(%22msg%22);%0A
     
@@ -2518,36 +2518,32 @@
 ) %7B%0A            
-    
 ZLog.logExceptio
@@ -2557,32 +2557,26 @@
         
-    %7D%0A  
+%7D%0A
         
   final 
@@ -2567,18 +2567,16 @@
         
-  
 final St
@@ -2604,20 +2604,16 @@
 essage;%0A
-    
         
@@ -2644,36 +2644,32 @@
 ew Runnable() %7B%0A
-    
             @Ove
@@ -2678,36 +2678,32 @@
 ide%0A            
-    
 public void run(
@@ -2698,36 +2698,32 @@
 ic void run() %7B%0A
-    
                 
@@ -2796,36 +2796,32 @@
                 
-    
 .show();%0A       
@@ -2805,36 +2805,32 @@
        .show();%0A
-    
             %7D%0A  
@@ -2839,426 +2839,11 @@
     
-    %7D);%0A            this.cancel(true);%0A        %7D else %7B%0A            activity.runOnUiThread(new Runnable() %7B%0A                @Override%0A                public void run() %7B%0A                    Toast.makeText(activity, %22Network error%22, Toast.LENGTH_LONG)%0A                            .show();%0A                %7D%0A            %7D);%0A            // supermethod invokes cancel for us%0A            super.handleHTTPError(e);%0A        %7D
+%7D);
 %0A   

Fix errorHandling in AsyncLogin