package com.ved.musicmapapp.adapters;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Typeface;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.andraskindler.quickscroll.Scrollable;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.ved.musicmapapp.R;
import com.ved.musicmapapp.Objects.Artist;
import com.ved.musicmapapp.Objects.Song;
import com.ved.musicmapapp.utils.SerialExecutor;
import com.ved.musicmapapp.utils.Statics;
import com.ved.musicmapapp.utils.Utils;
public class ArtistGroupedListAdapter extends BaseAdapter implements Scrollable{
private Activity cxt;
private LayoutInflater inflat;
private Pair<List<Artist>, List<Artist>> artists;
private ImageLoader imageLoader;
private DisplayImageOptions options;
// private int count = Statics.EXPAND_VIEW_COUNT;
private boolean isLike;
private SerialExecutor taskExecutor;
public ArtistGroupedListAdapter(Activity cxt,
Pair<List<Artist>, List<Artist>> artists, boolean isLike) {
this.cxt = cxt;
this.artists = artists;
this.isLike = isLike;
inflat = (LayoutInflater) cxt
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader = ImageLoader.getInstance();
options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.img_no_image)
.showImageForEmptyUri(R.drawable.img_no_image)
.showImageOnFail(R.drawable.img_no_image).cacheInMemory(true)
.cacheOnDisc(true).bitmapConfig(Bitmap.Config.RGB_565).build();
taskExecutor = new SerialExecutor(new ScheduledThreadPoolExecutor(3));
}
public void setData(Pair<List<Artist>, List<Artist>> artists) {
this.artists = artists;
notifyDataSetChanged();
}
@Override
public int getCount() {
return artists.first.size() + artists.second.size();
}
// public void updateCount(int count){
// this.count = count;
// notifyDataSetChanged();
// }
@Override
public long getItemId(int position) {
return -1;
}
@Override
public View getView(final int position, View v, ViewGroup parent) {
Artist artist = getItem(position);
if (v == null) {
v = inflat.inflate(R.layout.item_user_artist, parent, false);
}
// ImageView imv_like = (ImageView)v.findViewById(R.id.imv_like);
final ImageView imv_av = (ImageView) v.findViewById(R.id.imv_musician_av);
TextView tv_name = (TextView) v.findViewById(R.id.tv_name_musician);
Typeface tf = Typeface.createFromAsset(cxt.getAssets(), "open_sans_regular.ttf");
tv_name.setTypeface(tf);
tv_name.setText(artist.getName() + " -> " + artist.getLatUpdate()
% 10000000);
tv_name.setSelected(true);
if (artist.isHasArtist() || isLike) {
tv_name.setTextColor(cxt.getResources().getColor(
R.color.bg_title_bar));
} else {
tv_name.setTextColor(cxt.getResources()
.getColor(R.color.yellow_new));
}
TextView tvNoSong = (TextView) v.findViewById(R.id.tvNoSong);
Typeface tf1 = Typeface.createFromAsset(cxt.getAssets(), "open_sans_regular.ttf");
tvNoSong.setTypeface(tf1);
if (isLike) {
tvNoSong.setText(artist.getSongs().size() > 1 ? artist.getSongs()
.size() + " likes" : artist.getSongs().size() + " like");
} else {
tvNoSong.setText(artist.getSongs().size() > 1 ? cxt.getString(
R.string.user_details_tracks, artist.getSongs().size())
: cxt.getString(R.string.user_details_track, artist
.getSongs().size()));
}
imv_av.setImageResource(R.drawable.img_no_image);
if (artist.getAvatar().trim().length() > 0) {
imageLoader.displayImage(artist.getAvatar().trim(), imv_av, options,new ImageLoadingListener() {
@Override
public void onLoadingStarted(String imageUri, View view) {
}
@Override
public void onLoadingFailed(String imageUri, View view,
FailReason failReason) {
}
@Override
public void onLoadingComplete(String imageUri, View view,
Bitmap loadedImage) {
imv_av.setImageBitmap(loadedImage);
}
@Override
public void onLoadingCancelled(String imageUri, View view) {
}
});
} else {
try {
taskExecutor.execute(String.valueOf(getItem(position).getID()),
new Runnable() {
@Override
public void run() {
Artist at = getItem(position);
String avatar = loadAvatar(cxt, at);
if (avatar != null) {
Log.d("ARTIST", at.getName() + ": "
+ avatar);
boolean isContain = false;
for (Artist artist : artists.first) {
if (artist.getID() == at.getID()) {
artist.setAvatar(avatar);
mHandler.sendEmptyMessage(1);
isContain = true;
break;
}
}
if (!isContain) {
for (Artist artist : artists.second) {
if (artist.getID() == at.getID()) {
artist.setAvatar(avatar);
mHandler.sendEmptyMessage(1);
break;
}
}
}
}
}
});
} catch (Exception e) {
}
}
TextView tvSection = (TextView) v.findViewById(R.id.tv_section);
Typeface tf11 = Typeface.createFromAsset(cxt.getAssets(), "open_sans_regular.ttf");
tvSection.setTypeface(tf11);
View layoutSection = v.findViewById(R.id.layout_section);
if (isLike) {
layoutSection.setVisibility(View.GONE);
} else {
if (position < artists.first.size()) {
if (position == 0) {
int color = cxt.getResources().getColor(R.color.bg_title_bar);
// tvSection.setTextColor(color);
/*v.findViewById(R.id.line1).setBackgroundColor(color);
v.findViewById(R.id.line2).setBackgroundColor(color);*/
tvSection.setText(R.string.artist_math_with_you);
layoutSection.setBackgroundColor( cxt.getResources().getColor(R.color.blue_new_light));
layoutSection.setVisibility(View.VISIBLE);
} else {
layoutSection.setVisibility(View.GONE);
}
} else {
if (position - artists.first.size() == 0) {
int color = cxt.getResources().getColor(R.color.yellow_new);
// tvSection.setTextColor(color);
/* v.findViewById(R.id.line1).setBackgroundColor(color);
v.findViewById(R.id.line2).setBackgroundColor(color);*/
tvSection.setText(R.string.artist_others);
layoutSection.setVisibility(View.VISIBLE);
layoutSection.setBackgroundColor( color);
} else {
layoutSection.setVisibility(View.GONE);
}
}
}
return v;
}
@Override
public Artist getItem(int position) {
if (position < 0 && position >= getCount()) {
return null;
}
if (position < artists.first.size()) {
return artists.first.get(position);
} else {
return artists.second.get(position - artists.first.size());
}
}
private String loadAvatar(Context context, Artist artist) {
try {
if (!Statics.isNetworkConnected(context)) {
return null;
}
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Statics.WS_PATH
+ "getArtistAvatar.php");
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("artist_id", String.valueOf(artist
.getID())));
nvps.add(new BasicNameValuePair("artist_name", artist.getName()));
httppost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
if (entity != null) {
// get the response content as a string
InputStream instream = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(instream, "UTF-8"));
String line;
StringBuilder sb = new StringBuilder("");
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
return sb.toString();
}
} catch (UnsupportedEncodingException e1) {
Log.e("Exception", "" + e1.getMessage());
// e1.printStackTrace();
} catch (ClientProtocolException e1) {
Log.e("ClientProtocolException", "" + e1.getMessage());
// e1.printStackTrace();
} catch (IOException e1) {
Log.e("IOException", "load Avatar" + e1.getMessage());
e1.printStackTrace();
}
return null;
}
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
notifyDataSetChanged();
super.handleMessage(msg);
}
};
public void sortAscending(){
sortListAscending(artists.first);
notifyDataSetChanged();
sortListAscending(artists.second);
notifyDataSetChanged();
}
static void sortListAscending(List<?> list){
Collections.sort(list, new Comparator<Object>(){
public int compare(Object o1, Object o2) {
Artist p1 = (Artist) o1;
Artist p2 = (Artist) o2;
return p1.getName().compareTo(p2.getName());
}
});
}
@Override
public String getIndicatorForPosition(int childposition, int groupposition) {
Artist artist = getItem(childposition);
if(artist.getName() != null)
return String.valueOf(artist.getName().charAt(0)).toUpperCase();
else
return "";
}
@Override
public int getScrollPosition(int childposition, int groupposition) {
return childposition;
}
}