package cgeo.geocaching;

import cgeo.geocaching.activity.AbstractActivity;

import org.apache.commons.collections.CollectionUtils;

import android.app.ProgressDialog;
import android.location.Address;
import android.location.Geocoder;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;

import java.util.List;
import java.util.Locale;

public class cgeoaddresses extends AbstractActivity {
    private String keyword = null;
    private LayoutInflater inflater = null;
    private LinearLayout addList = null;
    private ProgressDialog waitDialog = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // init
        inflater = getLayoutInflater();

        setTheme();
        setContentView(R.layout.addresses);
        setTitle(res.getString(R.string.search_address_result));

        // get parameters
        Bundle extras = getIntent().getExtras();

        // try to get data from extras
        if (extras != null) {
            keyword = extras.getString("keyword");
        }

        if (keyword == null) {
            showToast(res.getString(R.string.err_search_address_forgot));
            finish();
            return;
        }

        waitDialog = ProgressDialog.show(this, res.getString(R.string.search_address_started), keyword, true);
        waitDialog.setCancelable(true);

        new AsyncTask<Void, Void, List<Address>>() {

            @Override
            protected List<Address> doInBackground(Void... params) {
                final Geocoder geocoder = new Geocoder(cgeoaddresses.this, Locale.getDefault());
                try {
                    return geocoder.getFromLocationName(keyword, 20);
                } catch (Exception e) {
                    Log.e(Settings.tag, "cgeoaddresses.doInBackground", e);
                    return null;
                }
            }

            @Override
            protected void onPostExecute(final List<Address> addresses) {
                waitDialog.dismiss();
                try {
                    if (addList == null) {
                        addList = (LinearLayout) findViewById(R.id.address_list);
                    }

                    if (CollectionUtils.isEmpty(addresses)) {
                        showToast(res.getString(R.string.err_search_address_no_match));
                        finish();
                        return;
                    } else {
                        LinearLayout oneAddPre = null;
                        for (Address address : addresses) {
                            oneAddPre = (LinearLayout) inflater.inflate(R.layout.address_button, null);

                            Button oneAdd = (Button) oneAddPre.findViewById(R.id.button);
                            int index = 0;
                            StringBuilder allAdd = new StringBuilder();
                            StringBuilder allAddLine = new StringBuilder();

                            while (address.getAddressLine(index) != null) {
                                if (allAdd.length() > 0) {
                                    allAdd.append('\n');
                                }
                                if (allAddLine.length() > 0) {
                                    allAddLine.append("; ");
                                }

                                allAdd.append(address.getAddressLine(index));
                                allAddLine.append(address.getAddressLine(index));

                                index++;
                            }

                            oneAdd.setText(allAdd.toString());
                            oneAdd.setLines(allAdd.toString().split("\n").length);
                            oneAdd.setClickable(true);
                            oneAdd.setOnClickListener(new buttonListener(address.getLatitude(), address.getLongitude(), allAddLine.toString()));
                            addList.addView(oneAddPre);
                        }
                    }
                } catch (Exception e) {
                    Log.e(Settings.tag, "cgeoaddresses.onPostExecute", e);
                }
            }

        }.execute();
    }

    @Override
    public void onResume() {
        super.onResume();

    }

    private class buttonListener implements View.OnClickListener {

        private final double latitude;
        private final double longitude;
        private final String address;

        public buttonListener(double latitudeIn, double longitudeIn, String addressIn) {
            latitude = latitudeIn;
            longitude = longitudeIn;
            address = addressIn;
        }

        public void onClick(View arg0) {
            cgeocaches.startActivityAddress(cgeoaddresses.this, latitude, longitude, address);
            finish();
            return;
        }
    }
}

@@ -68,16 +68,58 @@
 ctivity;
+%0Aimport cgeo.geocaching.geopoint.Geopoint;
 %0A%0Aimport
@@ -166,16 +166,61 @@
 onUtils;
+%0Aimport org.apache.commons.lang3.StringUtils;
 %0A%0Aimport
@@ -520,24 +520,52 @@
 earLayout;%0A%0A
+import java.util.ArrayList;%0A
 import java.
@@ -2755,24 +2755,120 @@
 Pre = null;%0A
+                        final Geopoint lastLoc = cgeoapplication.getInstance().getLastCoords();%0A
             
@@ -3110,16 +3110,17 @@
 utton);%0A
+%0A
         
@@ -3143,171 +3143,213 @@
     
-int index = 0;%0A                            StringBuilder allAdd = new StringBuilder();%0A                            StringBuilder allAddLine = new StringBuilder();%0A
+final int maxIndex = address.getMaxAddressLineIndex();%0A                            final ArrayList%3CString%3E lines = new ArrayList%3CString%3E();%0A                            for (int i = 0; i %3C= maxIndex; i++) %7B
 %0A   
@@ -3377,15 +3377,26 @@
     
-while (
+    String line = 
 addr
@@ -3419,24 +3419,10 @@
 ne(i
-ndex) != null) %7B
+);
 %0A   
@@ -3458,27 +3458,36 @@
 if (
-allAdd.length() %3E 0
+StringUtils.isNotBlank(line)
 ) %7B%0A
@@ -3526,26 +3526,22 @@
     
-allAdd.append('%5Cn'
+lines.add(line
 );%0A 
@@ -3605,104 +3605,96 @@
     
-    if (allAddLine.length() %3E 0) %7B%0A                                    allAddLine.append(
+%7D%0A%0A                            final String listTitle = StringUtils.join(lines, 
 %22; %22);%0A
+%0A
     
@@ -3709,38 +3709,54 @@
                 
-    %7D%0A
+if (lastLoc != null) %7B
 %0A               
@@ -3776,53 +3776,62 @@
     
-allAdd.append(address.getAddressLine(index));
+if (address.hasLatitude() && address.hasLongitude()) %7B
 %0A   
@@ -3863,59 +3863,129 @@
     
-allAddLine.append(address.getAddressLine(index
+    lines.add(cgBase.getHumanDistance(lastLoc.distanceTo(new Geopoint(address.getLatitude(), address.getLongitude()))
 ));%0A
-%0A
     
@@ -4016,16 +4016,9 @@
     
-index++;
+%7D
 %0A   
@@ -4088,32 +4088,44 @@
 setText(
-allAdd.toString(
+StringUtils.join(lines, %22%5Cn%22
 ));%0A    
@@ -4168,44 +4168,20 @@
 nes(
-allAdd.toString().split(%22%5Cn%22).length
+lines.size()
 );%0A 
@@ -4230,24 +4230,25 @@
 able(true);%0A
+%0A
             
@@ -4359,29 +4359,17 @@
 (), 
-allAddLine.toString()
+listTitle
 ));%0A

add distance to search results for search by address