package com.frozendevs.cache.cleaner.model.adapter;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.text.format.Formatter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.frozendevs.cache.cleaner.model.AppsListItem;
import com.frozendevs.cache.cleaner.R;

import java.lang.Override;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;

public class AppsListAdapter extends BaseAdapter implements AdapterView.OnItemClickListener {

    public static enum SortBy {
        APP_NAME,
        CACHE_SIZE
    }

    private List<AppsListItem> mItems, mFilteredItems;
    private Context mContext;

    private class ViewHolder {
        ImageView image;
        TextView name, size;
        String packageName;
    }

    public AppsListAdapter(Context context) {
        mContext = context;

        mItems = new ArrayList<AppsListItem>();
        mFilteredItems = new ArrayList<AppsListItem>();
    }

    @Override
    public int getCount() {
        return mFilteredItems.size();
    }

    @Override
    public AppsListItem getItem(int i) {
        return mFilteredItems.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public boolean hasStableIds() {
        return true;
    }

    @Override
    public View getView(int i, View convertView, ViewGroup viewParent) {
        if (convertView == null) {
            convertView = LayoutInflater.from(mContext).inflate(R.layout.list_item, viewParent, false);
        }

        ViewHolder viewHolder = (ViewHolder) convertView.getTag();

        if (viewHolder == null) {
            viewHolder = new ViewHolder();

            viewHolder.image = (ImageView) convertView.findViewById(R.id.app_icon);
            viewHolder.name = (TextView) convertView.findViewById(R.id.app_name);
            viewHolder.size = (TextView) convertView.findViewById(R.id.app_size);

            convertView.setTag(viewHolder);
        }

        AppsListItem item = getItem(i);

        viewHolder.image.setImageDrawable(item.getApplicationIcon());
        viewHolder.name.setText(item.getApplicationName());
        viewHolder.size.setText(Formatter.formatShortFileSize(mContext, item.getCacheSize()));
        viewHolder.packageName = item.getPackageName();

        return convertView;
    }

    public void setItems(List<AppsListItem> items, SortBy sortBy) {
        mItems = items;

        sort(sortBy);
    }

    public void filterAppsByName(String filter) {
        new AsyncTask<String, Void, Void>() {

            @Override
            protected Void doInBackground(String... params) {
                List<AppsListItem> filteredItems = new ArrayList<AppsListItem>();

                Locale current = mContext.getResources().getConfiguration().locale;

                for (AppsListItem item : mItems) {
                    if (item.getApplicationName().toLowerCase(current).contains(
                            params[0].toLowerCase(current))) {
                        filteredItems.add(item);
                    }
                }

                mFilteredItems = filteredItems;

                return null;
            }

            @Override
            protected void onPostExecute(Void result) {
                notifyDataSetChanged();
            }

        }.execute(filter);
    }

    public void clearFilter() {
        mFilteredItems = mItems;

        notifyDataSetChanged();
    }

    public void sort(SortBy sortBy) {
        new AsyncTask<SortBy, Void, Void>() {

            @Override
            protected Void doInBackground(final SortBy... params) {
                Collections.sort(mItems, new Comparator<AppsListItem>() {
                    @Override
                    public int compare(AppsListItem lhs, AppsListItem rhs) {
                        switch (params[0]) {
                            case APP_NAME:
                                return lhs.getApplicationName().compareToIgnoreCase(
                                        rhs.getApplicationName());

                            case CACHE_SIZE:
                                return (int) (rhs.getCacheSize() - lhs.getCacheSize());
                        }

                        return 0;
                    }
                });

                mFilteredItems = new ArrayList<AppsListItem>(mItems);

                return null;
            }

            @Override
            protected void onPostExecute(Void result) {
                notifyDataSetChanged();
            }

        }.execute(sortBy);
    }

    @Override
    public void onItemClick (AdapterView<?> parent, View view, int position, long id) {
        ViewHolder viewHolder = (ViewHolder) view.getTag();

        if (viewHolder != null && viewHolder.packageName != null) {
            Intent intent = new Intent();
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.setAction(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            intent.setData(Uri.parse("package:" + viewHolder.packageName));

            mContext.startActivity(intent);
        }
    }
}

@@ -469,26 +469,9 @@
 ner.
-model.AppsListItem
+R
 ;%0Aim
@@ -508,38 +508,28 @@
 ner.
-R;%0A%0Aimport java.lang.Override;
+model.AppsListItem;%0A
 %0Aimp
@@ -2808,36 +2808,50 @@
 k%3CString, Void, 
-Void
+List%3CAppsListItem%3E
 %3E() %7B%0A%0A         
@@ -2877,36 +2877,50 @@
       protected 
-Void
+List%3CAppsListItem%3E
  doInBackground(
@@ -3412,68 +3412,28 @@
     
-mFilteredItems = filteredItems;%0A%0A                return null
+return filteredItems
 ;%0A  
@@ -3504,38 +3504,94 @@
 PostExecute(
-Void result) %7B
+List%3CAppsListItem%3E result) %7B%0A                mFilteredItems = result;%0A
 %0A           
@@ -3847,20 +3847,39 @@
 , Void, 
-Void
+ArrayList%3CAppsListItem%3E
 %3E() %7B%0A%0A 
@@ -3921,20 +3921,39 @@
 otected 
-Void
+ArrayList%3CAppsListItem%3E
  doInBac
@@ -3978,32 +3978,118 @@
 By... params) %7B%0A
+                ArrayList%3CAppsListItem%3E items = new ArrayList%3CAppsListItem%3E(mItems);%0A%0A
                 
@@ -4105,18 +4105,17 @@
 ns.sort(
-mI
+i
 tems, ne
@@ -4750,92 +4750,25 @@
     
-mFilteredItems = new ArrayList%3CAppsListItem%3E(mI
+return i
 tems
-)
 ;%0A
-%0A                return null;%0A
+   
     
@@ -4764,35 +4764,32 @@
 ms;%0A            
-   
 %7D%0A%0A            @
@@ -4842,22 +4842,83 @@
 ute(
-Void result) %7B
+ArrayList%3CAppsListItem%3E result) %7B%0A                mFilteredItems = result;%0A
 %0A   
@@ -5044,17 +5044,16 @@
 temClick
- 
 (Adapter

Improve handling of async task results