<commit_before>package com.kaltura.playersdk;

import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

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

import android.app.Activity;
import android.app.KeyguardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.PowerManager;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.BounceInterpolator;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.RelativeLayout;

import com.google.android.gms.cast.CastDevice;
import com.kaltura.playersdk.chromecast.CastPlayer;
import com.kaltura.playersdk.chromecast.ChromecastHandler;
import com.kaltura.playersdk.events.KPlayerEventListener;
import com.kaltura.playersdk.events.KPlayerJsCallbackReadyListener;
import com.kaltura.playersdk.events.OnCastDeviceChangeListener;
import com.kaltura.playersdk.events.OnCastRouteDetectedListener;
import com.kaltura.playersdk.events.OnPlayerStateChangeListener;
import com.kaltura.playersdk.events.OnPlayheadUpdateListener;
import com.kaltura.playersdk.events.OnProgressListener;
import com.kaltura.playersdk.events.OnToggleFullScreenListener;
import com.kaltura.playersdk.types.PlayerStates;
import com.kaltura.playersdk.widevine.WidevineHandler;

/**
 * Created by michalradwantzor on 9/24/13.
 */
public class PlayerViewController extends RelativeLayout {
    public static String TAG = "PlayerViewController";
    public static String DEFAULT_HOST = "http://cdnbakmi.kaltura.com";
    public static String DEFAULT_HTML5_URL = "/html5/html5lib/v2.1.1/mwEmbedFrame.php";
    public static String DEFAULT_PLAYER_ID = "21384602";

    private VideoPlayerInterface mVideoInterface;
    private PlayerView mPlayerView;
    private WebView mWebView;
    private double mCurSec;
    private Activity mActivity;
    private double mDuration = 0;
    private OnToggleFullScreenListener mFSListener;
    private HashMap<String, ArrayList<KPlayerEventListener>> mKplayerEventsMap = new HashMap<String, ArrayList<KPlayerEventListener>>();
    private HashMap<String, KPlayerEventListener> mKplayerEvaluatedMap = new HashMap<String, KPlayerEventListener>();
    private KPlayerJsCallbackReadyListener mJsReadyListener;
    
    public String host = DEFAULT_HOST;
    public String html5Url = DEFAULT_HTML5_URL;
    public String playerId = DEFAULT_PLAYER_ID;
    
    private String mVideoUrl;
    private String mVideoTitle = "";
    private String mThumbUrl ="";
    
    private PlayerStates mState = PlayerStates.START;
    private PowerManager mPowerManager;

    public PlayerViewController(final Context context) {
        super(context);
        mPowerManager = (PowerManager) context.getSystemService(context.POWER_SERVICE);
     // Get a handler that can be used to post to the main thread
        Handler mainHandler = new Handler(context.getMainLooper());
        Runnable myRunnable = new Runnable() {
			@Override
			public void run() {
				if ( !ChromecastHandler.initialized )
				ChromecastHandler.initialize(context, new OnCastDeviceChangeListener() {

					@Override
					public void onCastDeviceChange(CastDevice oldDevice, CastDevice newDevice) {
						if ( ChromecastHandler.selectedDevice != null ) {
							notifyKPlayer("trigger", new String[] { "chromecastDeviceConnected" });
						} else {
							notifyKPlayer("trigger", new String[] { "chromecastDeviceDisConnected" });							
						}
						createPlayerInstance();
					}		
				},
				new OnCastRouteDetectedListener(){
					@Override
					public void onCastRouteDetected() {
						setChromecastVisiblity();
					}				
				});			
			}       	
        };
        mainHandler.post(myRunnable);	  
    }

    public PlayerViewController(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public PlayerViewController(Context context, AttributeSet attrs,
            int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
    }

    public void setOnFullScreenListener(OnToggleFullScreenListener listener) {
        mFSListener = listener;
    }
    
    public void setPlayerViewDimensions(int width, int height, int xPadding, int yPadding) {
    	setPadding(xPadding, yPadding, 0, 0);
    	int newWidth = width + xPadding;
    	int newHeight = height + yPadding;

    	ViewGroup.LayoutParams lp = getLayoutParams();
        if ( lp == null ) {
        	lp = new ViewGroup.LayoutParams( newWidth, newHeight );
        } else {
            lp.width = newWidth;
            lp.height = newHeight;
        }

        this.setLayoutParams(lp);
        if (mWebView != null) {
            ViewGroup.LayoutParams wvlp = mWebView.getLayoutParams();
            wvlp.width = newWidth;
            wvlp.height = newHeight;
            updateViewLayout(mWebView, wvlp);
        }
        if ( mPlayerView != null ) {
        	LayoutParams plp = (LayoutParams) mPlayerView.getLayoutParams();
        	plp.width = newWidth;
        	plp.height = newHeight;
        	if ( xPadding==0 && yPadding==0 ) {
        		plp.addRule(CENTER_IN_PARENT);        		
        	} else {
        		plp.addRule(CENTER_IN_PARENT, 0);
        	}
            updateViewLayout(mPlayerView, plp);
        }

        invalidate();
    	
    }

    public void setPlayerViewDimensions(int width, int height) {
    	setPlayerViewDimensions(width, height, 0, 0);
    }
    
    private void setChromecastVisiblity() {
    	if ( ChromecastHandler.routeInfos.size() > 0 ) {
			setKDPAttribute("chromecast", "visible", true);
		} else {
			setKDPAttribute("chromecast", "visible", false);						
		}
    }
    
    /**
     * Build player URL and load it to player view
     * @param partnerId partner ID
     * @param entryId entry ID
     * @param activity bounding activity
     */
    public void addComponents(String partnerId, String entryId, Activity activity) {
        String iframeUrl = host + html5Url + "?wid=_" + partnerId + "&uiconf_id=" + playerId + "&entry_id=" + entryId;
        addComponents( iframeUrl, activity );
    }

    /**
     * load given url to the player view
     * 
     * @param iframeUrl
     *            url to payer
     * @param activity
     *            bounding activity
     */
    public void addComponents(String iframeUrl, Activity activity) {	
        mActivity = activity;
        mCurSec = 0;
        ViewGroup.LayoutParams currLP = getLayoutParams();
        mPlayerView = new PlayerView(mActivity);
        
      //  super.addView(mPlayerView, currLP);
        
        LayoutParams lp = new LayoutParams(currLP.width, currLP.height);
        super.addView(mPlayerView, lp);
        
        mVideoInterface = mPlayerView;
        setPlayerListeners();
        createPlayerInstance();
        
        
        LayoutParams wvLp = new LayoutParams(currLP.width, currLP.height);
        mWebView = new WebView(mActivity);
        this.addView(mWebView, wvLp);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.setWebViewClient(new CustomWebViewClient());
        mWebView.setWebChromeClient(new WebChromeClient());
        mWebView.getSettings().setUserAgentString(
                mWebView.getSettings().getUserAgentString()
                        + " kalturaNativeCordovaPlayer");
        if (Build.VERSION.SDK_INT >= 11) {
            mWebView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        }

        mWebView.loadUrl(iframeUrl);
        mWebView.setBackgroundColor(0);
    }
    
    /**
     * create PlayerView / CastPlayer instance according to cast status
     */
    private void createPlayerInstance() {
    	if ( mVideoInterface != null ) {    		
    		mVideoInterface.removePlayheadUpdateListener();
    		if ( mVideoInterface instanceof CastPlayer )
    			mVideoInterface.stop();
    	}
    	
    	if ( ChromecastHandler.selectedDevice != null ) {
    		mVideoInterface = new CastPlayer(getContext(), mVideoTitle, null, null, mThumbUrl, mVideoUrl);
    	} else {
    		mVideoInterface = mPlayerView;
    	}
    	mVideoInterface.setStartingPoint( (int) (mCurSec * 1000) );
		setPlayerListeners();
    }

    /**
     * slides with animation according the given values
     * 
     * @param x
     *            x offset to slide
     * @param duration
     *            animation time in milliseconds
     */
    public void slideView(int x, int duration) {
        this.animate().xBy(x).setDuration(duration)
                .setInterpolator(new BounceInterpolator());
    }
    
    public void destroy() {
       this.stop();
    }

    // /////////////////////////////////////////////////////////////////////////////////////////////
    // VideoPlayerInterface methods
    // /////////////////////////////////////////////////////////////////////////////////////////////
    public boolean isPlaying() {
        return (mVideoInterface != null && mVideoInterface.isPlaying());
    }

    /**<commit_msg>#KMS-3040 #expose API to save last playback position<commit_after>package com.kaltura.playersdk;

import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

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

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.PowerManager;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.BounceInterpolator;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.RelativeLayout;

import com.google.android.gms.cast.CastDevice;
import com.kaltura.playersdk.chromecast.CastPlayer;
import com.kaltura.playersdk.chromecast.ChromecastHandler;
import com.kaltura.playersdk.events.KPlayerEventListener;
import com.kaltura.playersdk.events.KPlayerJsCallbackReadyListener;
import com.kaltura.playersdk.events.OnCastDeviceChangeListener;
import com.kaltura.playersdk.events.OnCastRouteDetectedListener;
import com.kaltura.playersdk.events.OnPlayerStateChangeListener;
import com.kaltura.playersdk.events.OnPlayheadUpdateListener;
import com.kaltura.playersdk.events.OnProgressListener;
import com.kaltura.playersdk.events.OnToggleFullScreenListener;
import com.kaltura.playersdk.types.PlayerStates;
import com.kaltura.playersdk.widevine.WidevineHandler;

/**
 * Created by michalradwantzor on 9/24/13.
 */
public class PlayerViewController extends RelativeLayout {
    public static String TAG = "PlayerViewController";
    public static String DEFAULT_HOST = "http://cdnbakmi.kaltura.com";
    public static String DEFAULT_HTML5_URL = "/html5/html5lib/v2.1.1/mwEmbedFrame.php";
    public static String DEFAULT_PLAYER_ID = "21384602";

    private VideoPlayerInterface mVideoInterface;
    private PlayerView mPlayerView;
    private WebView mWebView;
    private double mCurSec;
    private Activity mActivity;
    private double mDuration = 0;
    private OnToggleFullScreenListener mFSListener;
    private HashMap<String, ArrayList<KPlayerEventListener>> mKplayerEventsMap = new HashMap<String, ArrayList<KPlayerEventListener>>();
    private HashMap<String, KPlayerEventListener> mKplayerEvaluatedMap = new HashMap<String, KPlayerEventListener>();
    private KPlayerJsCallbackReadyListener mJsReadyListener;
    
    public String host = DEFAULT_HOST;
    public String html5Url = DEFAULT_HTML5_URL;
    public String playerId = DEFAULT_PLAYER_ID;
    
    private String mVideoUrl;
    private String mVideoTitle = "";
    private String mThumbUrl ="";
    
    private PlayerStates mState = PlayerStates.START;
    private PowerManager mPowerManager;

    public PlayerViewController(final Context context) {
        super(context);
        mPowerManager = (PowerManager) context.getSystemService(context.POWER_SERVICE);
     // Get a handler that can be used to post to the main thread
        Handler mainHandler = new Handler(context.getMainLooper());
        Runnable myRunnable = new Runnable() {
			@Override
			public void run() {
				if ( !ChromecastHandler.initialized )
				ChromecastHandler.initialize(context, new OnCastDeviceChangeListener() {

					@Override
					public void onCastDeviceChange(CastDevice oldDevice, CastDevice newDevice) {
						if ( ChromecastHandler.selectedDevice != null ) {
							notifyKPlayer("trigger", new String[] { "chromecastDeviceConnected" });
						} else {
							notifyKPlayer("trigger", new String[] { "chromecastDeviceDisConnected" });							
						}
						createPlayerInstance();
					}		
				},
				new OnCastRouteDetectedListener(){
					@Override
					public void onCastRouteDetected() {
						setChromecastVisiblity();
					}				
				});			
			}       	
        };
        mainHandler.post(myRunnable);	  
    }

    public PlayerViewController(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public PlayerViewController(Context context, AttributeSet attrs,
            int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
    }

    public void setOnFullScreenListener(OnToggleFullScreenListener listener) {
        mFSListener = listener;
    }
    
    public void setPlayerViewDimensions(int width, int height, int xPadding, int yPadding) {
    	setPadding(xPadding, yPadding, 0, 0);
    	int newWidth = width + xPadding;
    	int newHeight = height + yPadding;

    	ViewGroup.LayoutParams lp = getLayoutParams();
        if ( lp == null ) {
        	lp = new ViewGroup.LayoutParams( newWidth, newHeight );
        } else {
            lp.width = newWidth;
            lp.height = newHeight;
        }

        this.setLayoutParams(lp);
        if (mWebView != null) {
            ViewGroup.LayoutParams wvlp = mWebView.getLayoutParams();
            wvlp.width = newWidth;
            wvlp.height = newHeight;
            updateViewLayout(mWebView, wvlp);
        }
        if ( mPlayerView != null ) {
        	LayoutParams plp = (LayoutParams) mPlayerView.getLayoutParams();
        	plp.width = newWidth;
        	plp.height = newHeight;
        	if ( xPadding==0 && yPadding==0 ) {
        		plp.addRule(CENTER_IN_PARENT);        		
        	} else {
        		plp.addRule(CENTER_IN_PARENT, 0);
        	}
            updateViewLayout(mPlayerView, plp);
        }

        invalidate();
    	
    }

    public void setPlayerViewDimensions(int width, int height) {
    	setPlayerViewDimensions(width, height, 0, 0);
    }
    
    private void setChromecastVisiblity() {
    	if ( ChromecastHandler.routeInfos.size() > 0 ) {
			setKDPAttribute("chromecast", "visible", true);
		} else {
			setKDPAttribute("chromecast", "visible", false);						
		}
    }
    
    /**
     * Build player URL and load it to player view
     * @param partnerId partner ID
     * @param entryId entry ID
     * @param activity bounding activity
     */
    public void addComponents(String partnerId, String entryId, Activity activity) {
        String iframeUrl = host + html5Url + "?wid=_" + partnerId + "&uiconf_id=" + playerId + "&entry_id=" + entryId;
        addComponents( iframeUrl, activity );
    }

    /**
     * load given url to the player view
     * 
     * @param iframeUrl
     *            url to payer
     * @param activity
     *            bounding activity
     */
    public void addComponents(String iframeUrl, Activity activity) {	
        mActivity = activity;
        mCurSec = 0;
        ViewGroup.LayoutParams currLP = getLayoutParams();
        mPlayerView = new PlayerView(mActivity);
        
      //  super.addView(mPlayerView, currLP);
        
        LayoutParams lp = new LayoutParams(currLP.width, currLP.height);
        super.addView(mPlayerView, lp);
        
        mVideoInterface = mPlayerView;
        setPlayerListeners();
        createPlayerInstance();
        
        
        LayoutParams wvLp = new LayoutParams(currLP.width, currLP.height);
        mWebView = new WebView(mActivity);
        this.addView(mWebView, wvLp);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.setWebViewClient(new CustomWebViewClient());
        mWebView.setWebChromeClient(new WebChromeClient());
        mWebView.getSettings().setUserAgentString(
                mWebView.getSettings().getUserAgentString()
                        + " kalturaNativeCordovaPlayer");
        if (Build.VERSION.SDK_INT >= 11) {
            mWebView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        }

        mWebView.loadUrl(iframeUrl);
        mWebView.setBackgroundColor(0);
    }
    
    /**
     * create PlayerView / CastPlayer instance according to cast status
     */
    private void createPlayerInstance() {
    	if ( mVideoInterface != null ) {    		
    		mVideoInterface.removePlayheadUpdateListener();
    		if ( mVideoInterface instanceof CastPlayer )
    			mVideoInterface.stop();
    	}
    	
    	if ( ChromecastHandler.selectedDevice != null ) {
    		mVideoInterface = new CastPlayer(getContext(), mVideoTitle, null, null, mThumbUrl, mVideoUrl);
    	} else {
    		mVideoInterface = mPlayerView;
    	}
    	mVideoInterface.setStartingPoint( (int) (mCurSec * 1000) );
		setPlayerListeners();
    }

    /**
     * slides with animation according the given values
     * 
     * @param x
     *            x offset to slide
     * @param duration
     *            animation time in milliseconds
     */
    public void slideView(int x, int duration) {
        this.animate().xBy(x).setDuration(duration)
                .setInterpolator(new BounceInterpolator());
    }
    
    public void destroy() {
       this.stop();
    }
    
    public void savePlaybackPosition() {
    	if ( mVideoInterface!= null ) {
    		mVideoInterface.setStartingPoint( (int) (mCurSec * 1000) );
    	}
    }

    // /////////////////////////////////////////////////////////////////////////////////////////////
    // VideoPlayerInterface methods
    // /////////////////////////////////////////////////////////////////////////////////////////////
    public boolean isPlaying() {
        return (mVideoInterface != null && mVideoInterface.isPlaying());
    }

    /**
{'fraction_non_alphanumeric': 0.11049635580145768, 'fraction_numerical': 0.004575198169920732, 'mean_word_length': 2.702580263935395, 'pattern_counts': {'":': 0, '<': 15, '<?xml version=': 0, '>': 19, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7485948', 'n_tokens_mistral': 5693, 'n_tokens_neox': 5320, 'n_words': 1133}