/*
 * WR.java
 * classes : cn.com.wasu.main.jsobject.WR
 * @author Administrator
 * V 1.0.0
 * Create at 2014年10月16日 下午5:02:32
 */
package com.wasu.cs.jsobject;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;

import com.wasu.authsdk.AuthListener;
import com.wasu.authsdk.AuthSDK;
import com.wasu.authsdk.entity.PriceInfo;
import com.wasu.authsdk.entity.XHYYJEnquiryResult;
import com.wasu.common.WError;
import com.wasu.cs.module.LogReaderModule;
import com.wasu.cs.module.LogReaderModule.WRLogHolder.logUpLoadListener;
import com.wasu.cs.ui.ActivityLivePlayer;
import com.wasu.cs.ui.ActivityPlayer;
import com.wasu.module.log.WLog;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import cn.com.wasu.main.IntentConstant;
import cn.com.wasu.main.IntentMap;

/**
 * cn.com.wasu.main.jsobject.WR
 * 
 * @author zhangrm@wasu.com <br/>
 *         create at 2014年10月16日 下午5:02:32
 */
public class WR {
	private static final String TAG = "WR";
	//letv-super-sports packagename
	private static final String LETV_SUPERSPORT_PACKAGENAME = "com.lesports.tv";
	//migu-xuetang packagename
	private static final String MIGU_XUETANG_PACKAGENAME = "com.hschinamobile.hestudy";

	private Context mContext;
	private long preTimeMills;
	private WebView webView;

	public WR(Context context) {
		this.mContext = context;
	}

	public WR(Context mContext, WebView webView) {
		this.mContext = mContext;
		this.webView = webView;
	}

	@JavascriptInterface
	public void openDetail(String playUri) {
		try {
			long currTimeMills = System.currentTimeMillis();
			if (preTimeMills == 0 || currTimeMills - preTimeMills > 1000) {
				preTimeMills = currTimeMills;
				Intent intent = new Intent(Intent.ACTION_VIEW);
				intent.setData(Uri.parse(playUri));
				intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
				mContext.startActivity(intent);
			}
		} catch (Exception e) {
			e.toString();
		}
	}

	@JavascriptInterface
	public void openCollection() {
		try {
			Intent intent = new Intent("com.wasutv.action.opencollection");
			mContext.startActivity(intent);
		} catch (Exception e) {
			e.toString();
		}
	}

	@JavascriptInterface
	public void openHistory() {
		try {
			Intent intent = new Intent("com.wasutv.action.openhistory");
			mContext.startActivity(intent);
		} catch (Exception e) {
			e.toString();
		}
	}

	@JavascriptInterface
	public void layoutCommandHandle(String layoutCode, String jsonUrl, String extra) {
		Intent i = new Intent();
		if (extra == null) {
			extra = "";
		}

		i.putExtra("Extra", extra);
		IntentMap.startIntent(mContext, i, layoutCode, jsonUrl, null);
	}

	@JavascriptInterface
	public void loopPlay(String jsonUrl, int playIndex) {
		WLog.i(TAG,"loopPlay");
		if (TextUtils.isEmpty(jsonUrl)) {
			WLog.e(TAG, "loopPlay check params jsonUrl fail");
			return;
		}

		Intent intent = new Intent();
		intent.putExtra(IntentConstant.PLAY_TYPE.value(), ActivityPlayer.PLAY_TYPE_LOOP);
		intent.putExtra(IntentConstant.PLAY_INDEX.value(), playIndex);
		intent.putExtra(IntentConstant.DATAURI.value(), jsonUrl);
		IntentMap.startIntent(mContext, intent, null, null, ActivityPlayer.class);
	}

	@JavascriptInterface
	public void startApk(String json) {
		try {
			JSONObject jsonObj = new JSONObject(json);
			String actionName = jsonObj.optString("actionName");
			String packageName = jsonObj.optString("packageName");
			String download = jsonObj.optString("download");

			Intent intent = null;

			if(!TextUtils.isEmpty(packageName) && TextUtils.equals(packageName,LETV_SUPERSPORT_PACKAGENAME)){
				//special logic for letv-super-sport
				intent = new Intent(actionName);
				//letv-super-sport burrowContent will be added in the while circle bellow

				//just add flag according to doc
				intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

			}else if(!TextUtils.isEmpty(packageName) && TextUtils.equals(packageName,MIGU_XUETANG_PACKAGENAME)){
//				PackageManager pkgmng = TvApp.getContext().getPackageManager();
//				intent = pkgmng.getLaunchIntentForPackage(packageName);
//
//				//just add flag according to doc
//				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

				intent = new Intent();
				ComponentName cn = new ComponentName("com.hschinamobile.hestudy","com.chinamobile.hestudy.activity.LogoActivity");
				intent.setComponent(cn);
				intent.setAction("android.intent.action.MAIN");
			}else{
				if (!TextUtils.isEmpty(packageName)) {
					intent = mContext.getPackageManager().getLaunchIntentForPackage(packageName);
				}else{
					if (!TextUtils.isEmpty(actionName)) {
						intent = new Intent(actionName);
					}else {
						intent = new Intent(Intent.ACTION_VIEW);
					}
				}
			}

			/*if (!TextUtils.isEmpty(actionName) && !TextUtils.isEmpty(packageName)) {
				intent = new Intent();
				intent.setComponent(new ComponentName(packageName, actionName));
			} else if (!TextUtils.isEmpty(actionName)) {
				intent = new Intent(actionName);
			} else if (!TextUtils.isEmpty(packageName)) {
				intent = mContext.getPackageManager().getLaunchIntentForPackage(packageName);
			} else {
				intent = new Intent(Intent.ACTION_VIEW);
			}*/
			// 遍历其他参数
			Iterator<String> keys = jsonObj.keys();
			while (keys.hasNext()) {
				String key = keys.next();
				if (!"actionName".equals(key) && !"packageName".equals(key) && !"download".equals(key)) {
					intent.putExtra(key, jsonObj.getString(key));
				}
			}
			mContext.startActivity(intent);
		} catch (Exception e) {
			e.toString();
			WLog.e(TAG, e.getMessage());
		}
	}



	/**
	 * WR日志上传
	 * 
	 * @param callback
	 *            调用WebView方法的名字
	 */
	@JavascriptInterface
	public void logUpload(String callback) {
		final String callbackName = callback;
		LogReaderModule.WRLogHolder.upLoadLog(new logUpLoadListener() {

			@Override
			public void onResult(boolean isSuccessful) {
				// TODO Auto-generated method stub
				if (isSuccessful) {
					if (webView != null) {
						webView.loadUrl("javascript:" + callbackName + "('0')");
					}
				} else {
					if (webView != null) {
						webView.loadUrl("javascript:" + callbackName + "('1')");
					}
				}
			}
		});
	}

	/**
	 * 支持BS专题js方法调用直播播放器
	 */
	@JavascriptInterface
	public void livePlay(String jsonData, String currentResourceId, String extraJson) {
		if (TextUtils.isEmpty(jsonData)) {
			WLog.e(TAG, "调用livePlay方法入参为空");
			return;
		}

		try {
			Intent i = new Intent(ActivityLivePlayer.ACTION);
			i.putExtra(ActivityLivePlayer.ASSET_PLAY_INFO, jsonData);
			i.putExtra(ActivityLivePlayer.ASSET_CHANNEL_ID, currentResourceId);
			mContext.startActivity(i);
		} catch (Exception e) {
			e.printStackTrace();
			WLog.e(TAG, "调用livePlay方法出错");
		}
	}

	/**
	 * web页面调用询价接口
	 * 
	 * @param resourceId
	 *            资产ID
	 * @param resourceName
	 *            资产名称
	 * @param orderType
	 *            单点类型:在线观看为0,下载观看为1
	 * @param callback
	 *            客户端回调页面的提供的回调方法
	 * @author Danxingxi on 2016.3.14 具体用法参见：TV4.0客户端接口规范 2.2.1.7部分
	 */
	@JavascriptInterface
	public void queryPrice(String resourceId, String resourceName, String orderType, String callback) {

		final String mCallBack = callback;

		Map<String, Object> params = new HashMap<String, Object>();
		params.put("resourceId", resourceId);
		params.put("resourceName", resourceName);
		params.put("orderType", orderType);

		AuthSDK.getInstance().queryPrice(params, new AuthListener() {

			@Override
			public void result(int error, String extraMsg, Object jsondata) {
				/** 标记询价是否成功： 0 成功，1 失败 **/
				int isSuccess = -1;
				/** 价格 **/
				double price = -1;
				/** 原价 **/
				double originalPrice = -1;
				if (error == WError.ERROR_NONE && jsondata != null) {
					isSuccess = 0;
					PriceInfo priceInfo = (PriceInfo) jsondata;
					price = priceInfo.mPrice;
					originalPrice = priceInfo.mOriginalPrice;
				} else {
					isSuccess = 1;
					WLog.d(TAG, "WR queryPrice error");
				}
				if (webView != null) {
					webView.loadUrl("javascript:" + mCallBack + "('" + isSuccess + "', '" + price + "', '" + originalPrice + "')");
				} else {
					WLog.e(TAG, "WR webView == null");
				}
			}
		});
	}

	/**
	 * BS页面调用是否订包查询接口（订包查询接口和免广告接口对应于UPM为同一个接口）
	 * 
	 * @param callback
	 *            客户端回调页面的提供的回调方法（返回查询结果）
	 * @author Danxingxi on 2016.3.14 具体用法参见：TV4.0客户端接口规范 2.2.1.8部分
	 */
	@JavascriptInterface
	public void isOrderVIP(final String callback) {
		AuthSDK.getInstance().verifyUserIsAdFree(new AuthListener() {
			/** 0,不免 1,免 **/
			int isFree = -1;

			@Override
			public void result(int error, String extraMsg, Object jsondata) {
				if (error == WError.ERROR_NONE && jsondata != null) {
					try {
						JSONObject root = new JSONObject(new String((byte[]) jsondata, "utf-8"));
						isFree = root.optInt("isFree");
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
					} catch (JSONException e) {
						WLog.e(TAG, "WR isOrderVIP error");
						e.printStackTrace();
					}
					if (webView != null) {
						webView.loadUrl("javascript:" + callback + "('" + isFree + "')");
					}
				} else {
					WLog.e(TAG, "WR isOrderVIP error");
				}
			}
		});
	}

	/**
	 * web页面调用活动询价接口
	 * 
	 * @param jsonquery
	 *            页面调用接口需下发的json询价参数
	 * @param callback
	 *            客户端回调页面的提供的回调方法（返回询价结果） 具体用法参见：TV4.0客户端接口规范 2.2.1.9部分
	 */
	@JavascriptInterface
	public void actQueryPrice(String jsonquery, final String callback) {

		try {
			JSONObject root = new JSONObject(jsonquery);
			String resourceId = root.optString("resourceId");
			String resourceName = root.optString("resourceName");
			String queryType = root.optString("queryType");

			Map<String, Object> params = new HashMap<String, Object>();
			params.put("resourceId", resourceId);
			params.put("resourceName", resourceName);
			params.put("queryType", queryType);

			AuthSDK.getInstance().xhyyjEnquiry(params, new AuthListener() {

				@Override
				public void result(int error, String extraMsg, Object jsondata) {
					/** 标记询价是否成功： 0 成功，1 失败 **/
					int isSuccess = -1;
					/** 价格 **/
					double price = -1;
					/** 原价 **/
					double originalPrice = -1;
					/** 剩余时间 **/
					int remainingFreeWatchTime = -1;

					if (error == WError.ERROR_NONE && jsondata != null) {
						isSuccess = 0;
						XHYYJEnquiryResult enquiryResult = (XHYYJEnquiryResult) jsondata;
						price = enquiryResult.getPrice();
						originalPrice = enquiryResult.getOriginalPrice();
						remainingFreeWatchTime = enquiryResult.getRemainingFreeWatchTime();
					} else {
						isSuccess = 1;
						WLog.e(TAG, "WR actQueryPrice error");
					}
					if (webView != null) {
						webView.loadUrl("javascript:" + callback + "('" + isSuccess + "', '" + price + "', '" + originalPrice + "','" + remainingFreeWatchTime + "')");
					}
				}
			});

		} catch (JSONException e) {
			WLog.e(TAG, "WR actQueryPrice error");
			e.printStackTrace();
		}
	}
}
