package com.adviewbid.demo;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.kuaiyou.loader.AdViewNativeManager;
import com.kuaiyou.loader.loaderInterface.AdViewNativeListener;
import com.adviewbid.demo.R;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RadioGroup;
import android.widget.TextView;

import org.apache.http.conn.ssl.BrowserCompatHostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
/**
 * native ads
 * 
 * @author YYZ
 * useNative2
 */
public class AdNativeActivity extends Activity implements OnClickListener {
	private PopupWindow popupWindow = null;
	private boolean useNative2 = true;
	private boolean isScrollMode = false;
	private AdViewNativeListener advListener;
	private AdViewNativeManager adViewNative = null;
	private List<ViewHolder> mData = null;

    private final static int NATIVE_AD_UPDATE = 98;
	private final static int NATIVE_AD_RECEIVED = 99;
	private List native_AdList;

	private void requestAd() {
	    if (null != adViewNative) {
            adViewNative.omsdkNativeStopSession();
        }
		adViewNative = new AdViewNativeManager(this,
				MainActivity.offical_APPID,
				MainActivity.offical_native_posid,
				advListener);

		adViewNative.setGDPR2(1,
				MainActivity.Gdpr);

		adViewNative.requestAd();
		//clear listview
		if (useNative2) {
			//do nothing
		}else {
			ListView listView = (ListView) findViewById(R.id.listView);
			listView.setAdapter(null);
		}
	}

	private Handler updateHandler = new Handler(Looper.getMainLooper()) {
		public void handleMessage(Message msg) {
			try {
				switch (msg.what) {
					case NATIVE_AD_UPDATE:
						if (useNative2 || isScrollMode) {
							createNormalView();
						}else {
						createListView();
						}
						// 汇报展示
						if(mData.size() > 0) {
							ViewHolder holder = mData.get(0);
							View v = null;
							if (useNative2 || isScrollMode) {
								v = findViewById(R.id.image);
							}else {
								v = (ListView) findViewById(R.id.listView);
							}
							adViewNative.reportImpression(v, holder.str_adID);
						}
						break;
					case NATIVE_AD_RECEIVED:
						if (null != native_AdList && !native_AdList.isEmpty()) {
							new Thread(new Runnable(){
								@Override
								public void run() {
									getListData();
								}
							}).start();
						}
						View v2 = null;
						if (useNative2) {
							v2 = findViewById(R.id.image);
						}else {
							v2 = (ListView) findViewById(R.id.listView);
						}
						adViewNative.omsdkNativeCreateSession(v2);
						break;

					default:
						Log.i("Native:", "other events " );
						break;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		int mode  = getIntent().getExtras().getInt("native_mode", -1);
		if (mode == 1)
			isScrollMode = true;

		if (isScrollMode) {
			//setContentView(R.layout.activity_native2_scroll);
		} else {
			if (useNative2) {
				setContentView(R.layout.activity_native2);
			} else {
				setContentView(R.layout.activity_native);
			}
		}
		Button nextNative = (Button) findViewById(R.id.native_change);
		Button nativeBack = (Button) findViewById(R.id.native_back);
		nextNative.setOnClickListener(this);
		nativeBack.setOnClickListener(this);
		popupWindow = new PopupWindow(this);
		advListener = new com.kuaiyou.loader.loaderInterface.AdViewNativeListener() {
			/**
			 * 请求失败时调用该方法
			 *
			 * @param arg0
			 *            失败信息
			 *
			 */
			@Override
			public void onNativeAdReceiveFailed(String arg0) {
				Log.i("AdNativeActivity", "onNativeAdReceiveFailed " + arg0);
				if (null != adapter )
					adapter.clear();
			}
			/**
			 * 当请求成功时调用该方法
			 *
			 * @param nativeAdList
			 *            类型为List<HashMap<String,Object>>，返回得字段内容如下：
			 *            title--> 广告标题
			 *            adImage-->大图url
			 *            adIcon--> Icon图片链接
			 *            adFlagLogo--> 广告logo
			 *            desc--> 广告描述文字
			 *            sec_description--> 广告描述文字2
			 * 请着重关注 title,adImage,adIcon,desc 这四个字段
			 */
			@Override
			public void onNativeAdReceived(List nativeAdList) {
				Log.i("AdNativeActivity", "onNativeAdReceived");
				native_AdList = nativeAdList;
				//send message to ui thread
				Message message = new Message();
				Bundle bundle = new Bundle();
				message.what = NATIVE_AD_RECEIVED;
				message.setData(bundle);
				updateHandler.sendMessage(message);
			}
			@Override
			public void onDownloadStatusChange(int arg0) {

			}
			@Override
			public void onNativeAdClosed(View view) {

			}
		};

		requestAd();
	}

	private void onBack() {
		if (null != popupWindow && popupWindow.isShowing()) {
			popupWindow.dismiss();
		}
		else {
            adViewNative.omsdkNativeStopSession();
			this.finish();
		}
	}

	@Override
	public void onBackPressed() {
		//super.onBackPressed();
		//Log.i("AdNativeActivity", "!! onBackPressed() !!");
		onBack();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.native_back:
			onBack();
			break;
		case R.id.native_change:
			if (null != popupWindow && !popupWindow.isShowing()) {
				requestAd();
			}
			break;
		default:
			Log.i("AdNativeActivity", "! onClick() : other events !");
			break;
		}
	}


	///////////////////////////////////aimed functions///////////////////////////////////////////////

	/**
	 * get pic from remote
	 * @param url
	 * @return
	 */
	private Bitmap getHttpBitmap(String url){
		URL myFileURL;
		Bitmap bitmap=null;
		HttpURLConnection conn;
		try{
			myFileURL = new URL(url);
			//获得连接
			if (url.startsWith("https://")) {
				conn = (HttpsURLConnection) myFileURL.openConnection();
				((HttpsURLConnection) conn).setHostnameVerifier(new BrowserCompatHostnameVerifier());

			} else {
				conn = (HttpURLConnection) myFileURL.openConnection();
			}
			//HttpURLConnection conn=(HttpURLConnection)myFileURL.openConnection();
			//设置超时时间为6000毫秒，conn.setConnectionTiem(0);表示没有时间限制
			conn.setConnectTimeout(6000);
			//连接设置获得数据流
			conn.setDoInput(true);
			//不使用缓存
			conn.setUseCaches(false);
			//这句可有可无，没有影响
			//conn.connect();
			//得到数据流
			InputStream is = conn.getInputStream();
			//解析得到图片
			bitmap = BitmapFactory.decodeStream(is);
			//关闭数据流
			is.close();
		}catch(Exception e){
		    Log.i("AdNativeActivity", "!!!!!! can not got url :" + url + "resource !!!!!");
			e.printStackTrace();
		}

        return bitmap;

	}

	/////////////////////////////////// list /////////////////////////////////////////////////////

	public final class ViewHolder {
		//item holder
		public Bitmap privacyImg = null;
		public Bitmap contentImg = null;
		public Bitmap iconImg = null;
		public Bitmap adiconImg = null;
		public Bitmap adlogoImg = null;

		public String videoURL = "";
		public String str_desc = "";
		public String str_desc2 = "";
		public String str_title = "";
		public String str_iconUrl = "";
		public String str_pclickUrl = "";
		public String str_adID = "";

	}

		//mData = getListData();
		//mData.clear();

	//获取动态数组数据 可以由其他地方传来(json等)
	private void getListData() {
		if (null == mData) {
			mData = new ArrayList<ViewHolder>();
		}else {
			mData.clear();
		}
		ViewHolder holder = null;
		for(int i = 0; i < native_AdList.size(); i++)
		{
			holder = new ViewHolder();
			HashMap<String, Object> nativeAd = (HashMap) native_AdList.get(i);
			//set item value
			if (!nativeAd.toString().contains("videoUrl")) {
				//得到可用的图片
						if (null != nativeAd.get("privacy_image")) {
							String url = ((CharSequence) nativeAd.get("privacy_image")).toString();
							holder.privacyImg = getHttpBitmap(url);
						}
						if (null != nativeAd.get("adImage")) {
							int w = Integer.parseInt((nativeAd.get("imageWidth")).toString());
							int h = Integer.parseInt((nativeAd.get("imageHeight")).toString());
							if(w == h) {
								//set icon , not image
								String icon_url = ((CharSequence) nativeAd.get("adImage")).toString();
								holder.iconImg = getHttpBitmap(icon_url);
							}else {
								//if (nativeAd.get("adImage")))
								String urlAD = ((CharSequence) nativeAd.get("adImage")).toString();
								holder.contentImg = getHttpBitmap(urlAD);
							}
						}
						if (null != nativeAd.get("adFlagIcon")) {
							String adicon_url = ((CharSequence) nativeAd.get("adFlagIcon")).toString();
							holder.adiconImg = getHttpBitmap(adicon_url);
						}
						if (null != nativeAd.get("adFlagLogo")) {
							String adlogo_url = ((CharSequence) nativeAd.get("adFlagLogo")).toString();
							holder.adlogoImg = getHttpBitmap(adlogo_url);
						}

						if (null != nativeAd.get("description")) {
							holder.str_desc = ((CharSequence) nativeAd.get("description")).toString();
						}
						if (null != nativeAd.get("sec_description")) {
							holder.str_desc2 = ((CharSequence) nativeAd.get("sec_description")).toString();
						}
						holder.str_title = ((CharSequence) nativeAd.get("title")).toString();
						if (null != nativeAd.get("adIcon")) {
							holder.str_iconUrl = ((CharSequence) nativeAd.get("adIcon")).toString();
						}
						if (null != nativeAd.get("privacy_click")) {
							holder.str_pclickUrl = ((CharSequence) nativeAd.get("privacy_click")).toString();
						}
						if (null != nativeAd.get("adId")) {
							holder.str_adID = ((CharSequence) nativeAd.get("adId")).toString();
						}
			}else {
				holder.videoURL = ((CharSequence)nativeAd.get("videoUrl")).toString();
			}
			mData.add(holder);
		}
		//all done
		Message message = new Message();
		message.what = NATIVE_AD_UPDATE;
		updateHandler.sendMessage(message);
		return;
	}
	//////////////////////////////normal view ////////////////////////////////////////
	private void createNormalView() {
		{
			//set UI item value
			int position = 0;
			ImageView iconView = (ImageView) findViewById(R.id.icon);
			ImageView adContentView = (ImageView) findViewById(R.id.image);
			ImageView privacyView = (ImageView) findViewById(R.id.picon);

			TextView title = (TextView) findViewById(R.id.title);
			TextView desc = (TextView) findViewById(R.id.desc);
			TextView desc2 = (TextView) findViewById(R.id.desc2);
			ImageView adIconView = (ImageView)findViewById(R.id.adicon);
			ImageView adLogoView = (ImageView)findViewById(R.id.adlogo);
			View mainView = (View)findViewById(R.id.ad_content_view);

			ViewHolder holder = null;
			holder = mData.get(position);
			desc.setText(holder.str_desc);
			desc2.setText(holder.str_desc2);
			title.setText(holder.str_title);
			
			if (isScrollMode) {
				//scroll mode
			}
			//点击privacy information打开
			privacyView.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					//show privacy information
					ViewHolder hold = mData.get(position);
					if (null != hold.privacyImg) {
						adViewNative.showPrivacyInfo(); //use sdk's show method
					}
				}
			});

			//点击落地页打开
			mainView.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					ViewHolder hold = mData.get(position);
					if (null != v) {
						// 触发点击汇报
						adViewNative.reportClick(
								v,
								hold.str_adID,
								(int) 0,
								(int) 0);
					}
				}
			});

            adContentView.setOnClickListener(new View.OnClickListener()  {
            @Override
            public void onClick(View v) {
                ViewHolder hold = mData.get(position);
                if (null != v) {
                    // 触发点击汇报
                    adViewNative.reportClick(
                            v,
                            hold.str_adID,
                            (int) 0,
                            (int) 0);
                }
            }
            });

			if (null != holder.iconImg) {
				iconView.setImageBitmap(holder.iconImg);
				iconView.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						ViewHolder hold = mData.get(position);
						if (null != v) {
							// 触发点击汇报
							//v.performClick();
							adViewNative.reportClick(
									v,
									hold.str_adID,
									(int) 0,
									(int) 0);
						}
					}
				});
			}else {
				iconView.setVisibility(View.GONE);
			}

			if (null != privacyView) {
				privacyView.setImageBitmap(holder.privacyImg);
			}
			if (null != adContentView) {
				if (null != holder.contentImg)
					adContentView.setImageBitmap(holder.contentImg);
				//adContentView.setVisibility(View.GONE);
			}
			if (null != adLogoView)
				adLogoView.setImageBitmap(holder.adlogoImg);
			if (null != adIconView)
				adIconView.setImageBitmap(holder.adiconImg);
			//popupWindow.update();
		}
	}

	////////////////////////////// list view /////////////////////////////////////
	private static MyAdapter adapter = null;
	public void createListView() {
		ListView listView = (ListView) findViewById(R.id.listView);
		//mData.clear();
		adapter = new MyAdapter(this);
		listView.setAdapter(adapter);
	}

	public class MyAdapter extends BaseAdapter {

		private LayoutInflater mInflater;

		public MyAdapter(Context context) {
			this.mInflater = LayoutInflater.from(context);
		}

		public void clear() {
			mData.clear();
			notifyDataSetChanged();
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return native_AdList.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}
		//****************************************final method *******************************
		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			ViewHolder holder = null;
			if (mData.size() <= 0) {
				LayoutInflater inflater = LayoutInflater.from(getBaseContext());
				convertView = inflater.inflate(R.layout.item4, null);
				return convertView;
			}
			if (convertView == null) {
				//holder=new ViewHolder();
				holder = mData.get(position);
				//可以理解为从vlist获取view 之后把view返回给ListView
				LayoutInflater inflater = LayoutInflater.from(getBaseContext());
				convertView = inflater.inflate(R.layout.item4, null);
				convertView.setTag(holder);

			}else {
				holder = (ViewHolder)convertView.getTag();
			}
			//set UI item value
			//WebView icon = (WebView) convertView.findViewById(R.id.icon);
			//WebView image = (WebView) contentView.findViewById(R.id.image);
			ImageView iconView = (ImageView) convertView.findViewById(R.id.icon);
			ImageView adContentView = (ImageView) convertView.findViewById(R.id.image);
			ImageView privacyView = (ImageView) convertView.findViewById(R.id.picon);

			TextView title = (TextView) convertView.findViewById(R.id.title);
			TextView desc = (TextView) convertView.findViewById(R.id.desc);
			TextView desc2 = (TextView) convertView.findViewById(R.id.desc2);
			ImageView adIconView = (ImageView)convertView.findViewById(R.id.adicon);
			ImageView adLogoView = (ImageView)convertView.findViewById(R.id.adlogo);

			{
				desc.setText(holder.str_desc);
				desc2.setText(holder.str_desc2);
				title.setText(holder.str_title);
				//点击落地页打开
				privacyView.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						//show privacy information
						ViewHolder hold = mData.get(position);
						if (null != hold.privacyImg) {
							adViewNative.showPrivacyInfo(); //use sdk's show method
						}
					}
				});

				//点击落地页打开，widler 20191011 改为点击list的item任意都可以触发click事件
				convertView.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						ViewHolder hold = mData.get(position);
						if (null != v) {
							// 触发点击汇报
							//v.performClick();
							adViewNative.reportClick(
									v,
									hold.str_adID,
									(int) 0,
									(int) 0);
						}
					}
				});

				if (null != holder.iconImg) {
					iconView.setImageBitmap(holder.iconImg);
					iconView.setOnClickListener(new View.OnClickListener() {
						@Override
						public void onClick(View v) {
							ViewHolder hold = mData.get(position);
							if (null != v) {
								// 触发点击汇报
								//v.performClick();
								adViewNative.reportClick(
										v,
										hold.str_adID,
										(int) 0,
										(int) 0);
							}
						}
					});
				}else {
					iconView.setVisibility(View.GONE);
				}

				if (null != privacyView) {
					privacyView.setImageBitmap(holder.privacyImg);
				}
				if (null != adContentView) {
					if (null != holder.contentImg)
						adContentView.setImageBitmap(holder.contentImg);
					//adContentView.setVisibility(View.GONE);
				}
				if (null != adLogoView)
					adLogoView.setImageBitmap(holder.adlogoImg);
				if (null != adIconView)
					adIconView.setImageBitmap(holder.adiconImg);
			}

			return convertView;
		}
	}
}
