package com.viaccessorca.voplayerdemo;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.nio.ByteBuffer;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.Toast;

import com.viaccessorca.voplayerdemo.activities.PlayerActivity;
import com.viaccessorca.voplayerdemo.database.DatabaseInfo;
import com.viaccessorca.voplayerdemo.mediamgt.MediaItem;
import com.viaccessorca.voplayerdemo.mediamgt.StreamingMediaItem;
import com.viaccessorca.voplayerdemo.mediamgt.StreamingMediaList;

public class Utils {


    public static void fillIntentWithMediaItem(Intent i, MediaItem mediaItem) {

        Uri mediaUri;
        mediaUri = Uri.parse(mediaItem.getMediaUri());

        MediaItem.MediaType type = mediaItem.getMediaType();
        if (MediaItem.MediaType.HTTP_STREAMING_MEDIA == type
                || MediaItem.MediaType.HTTP_STREAMING_MEDIA_EBD == type) {

            StreamingMediaItem streamingItem = (StreamingMediaItem) mediaItem;

            if (null != streamingItem.getBootAddress() &&
                    null != streamingItem.getCompanyName()) {
                i.putExtra(Constants.VCAS_BOOT_ADDRESS_INTENT_SKEY,
                        streamingItem.getBootAddress());
                i.putExtra(Constants.VCAS_COMPANY_NAME_INTENT_SKEY,
                        streamingItem.getCompanyName());
            }

            if (null != streamingItem.getSecondaryContentUri()) {
                i.putExtra(Constants.SECONDARY_CONTENT_URI_SKEY,
                        streamingItem.getSecondaryContentUri());
            }

            if (null != streamingItem.getDrmAgentType()) {
                i.putExtra(Constants.DRM_AGENT_TYPE,
                        streamingItem.getDrmAgentType());
            }

            if (null != streamingItem.getDrmPersonalizationUrl()) {
                i.putExtra(Constants.DRM_PERSONALIZATION_URL,
                        streamingItem.getDrmPersonalizationUrl());
            }

            if (null != streamingItem.getDrmPersonalizationAppVersion()) {
                i.putExtra(Constants.DRM_PERSONALIZATION_APPVERSION,
                        streamingItem.getDrmPersonalizationAppVersion());
            }

            if (null != streamingItem.getDrmPersonalizationCustomData()) {
                i.putExtra(Constants.DRM_PERSONALIZATION_CUSTOM_DATA,
                        streamingItem.getDrmPersonalizationCustomData());
            }

            if (null != streamingItem.getDrmPersonalizationCustomerID()) {
                i.putExtra(Constants.DRM_PERSONALIZATION_CUSTOMER_ID,
                        streamingItem.getDrmPersonalizationCustomerID());
            }

            if (null != streamingItem.getDRMLicenseAcquisitionUrl()) {
                i.putExtra(Constants.DRM_LICENSE_URL_SKEY,
                        streamingItem.getDRMLicenseAcquisitionUrl());
            }

            if (null != streamingItem.getDRMLicenseAcquisitionUrlParameters()) {
                i.putExtra(Constants.DRM_LICENSE_URL_PARAMETERS_SKEY,
                        streamingItem.getDRMLicenseAcquisitionUrlParameters());
            }

            if (null != streamingItem.getDRMLicenseAcquisitionCustomData()) {
                i.putExtra(Constants.DRM_LICENSE_CUSTOM_DATA_SKEY,
                        streamingItem.getDRMLicenseAcquisitionCustomData());
            }

            if (null != streamingItem.getDRMLicenseAcquisitionCookie()) {
                i.putExtra(Constants.DRM_LICENSE_COOKIE_SKEY,
                        streamingItem.getDRMLicenseAcquisitionCookie());
            }

			if (null != streamingItem.getDrmContentIdentifier()) {
				i.putExtra(Constants.DRM_CONTENT_IDENTIFIER,
						streamingItem.getDrmContentIdentifier());
			}

			i.putExtra(Constants.DRM_LICENSE_USE_VOSECURITYGATEWAY,
					streamingItem.useVOSecurityGateway());

			i.putExtra(Constants.FLAT_360_PLAYBACK_SUPPORT, streamingItem.get360Content());

            i.putExtra(Constants.MARLIN_PROTECTED_SKEY, streamingItem.getMarlinProtected());
            
            if (null != streamingItem.getVastUrl()){
                i.putExtra(Constants.VAST_URL_INTENT_SKEY, streamingItem.getVastUrl());
            }
            if (null != streamingItem.getVmapUrl()){
                i.putExtra(Constants.VMAP_URL_INTENT_SKEY, streamingItem.getVmapUrl());
            }
            
            i.putExtra(Constants.FAST_STARTUP_BKEY, streamingItem.getFastStartup());
            i.putExtra(Constants.LOCAL_SERVER_DEMO_BKEY, streamingItem.getLocalServerDemo());

            if (null != streamingItem.getDbFaasOffline()) {
                i.putExtra(Constants.DB_FAAS_OFFLINE_SKEY,
                        streamingItem.getDbFaasOffline());
            }

            if (null != streamingItem.getHttpAuthUsername() &&
                    null != streamingItem.getHttpAuthPassword()) {
                i.putExtra(Constants.AUTH_USER_NAME_INTENT_SKEY,
                        streamingItem.getHttpAuthUsername());
                i.putExtra(Constants.AUTH_PASSWORD_INTENT_SKEY,
                        streamingItem.getHttpAuthPassword());
            }

            if (null != streamingItem.getSSLCACertFilePath() &&
                    null != streamingItem.getSSLCACertFileType()) {
                i.putExtra(Constants.SSL_CA_CERT_FILE_PATH_INTENT_SKEY,
                        streamingItem.getSSLCACertFilePath());
                i.putExtra(Constants.SSL_CA_CERT_FILE_TYPE_INTENT_SKEY,
                        streamingItem.getSSLCACertFileType());
            }

            if (null != streamingItem.getSSLClientCertFilePath() &&
                    null != streamingItem.getSSLClientCertFileType()) {
                i.putExtra(Constants.SSL_CLIENT_CERT_FILE_PATH_INTENT_SKEY,
                        streamingItem.getSSLClientCertFilePath());
                i.putExtra(Constants.SSL_CLIENT_CERT_FILE_TYPE_INTENT_SKEY,
                        streamingItem.getSSLClientCertFileType());
            }

            if (null != streamingItem.getSSLClientKeyFilePath() &&
                    null != streamingItem.getSSLClientKeyFileType()) {
                i.putExtra(Constants.SSL_CLIENT_KEY_FILE_PATH_INTENT_SKEY,
                        streamingItem.getSSLClientKeyFilePath());
                i.putExtra(Constants.SSL_CLIENT_KEY_FILE_TYPE_INTENT_SKEY,
                        streamingItem.getSSLClientKeyFileType());
            }

            if (null != streamingItem.getHttpCustomHeader()) {
                i.putExtra(Constants.HTTP_CUSTOM_HEADER_INTENT_SKEY,
                        streamingItem.getHttpCustomHeader());
            }
            if (null != streamingItem.getStreamBitrates()) {
                i.putExtra(Constants.HLS_CUSTOM_BITRATES_ZERO_LAG_AIKEY, streamingItem.getStreamBitrates());
            }
            if (null != streamingItem.getAbrSensitivityValue()) {
                i.putExtra(Constants.PREF_ENABLE_ABR_SENSITIVITY, streamingItem.getAbrSensitivityValue());
            }
            i.putExtra(Constants.ABR_LIVE_LATENCY_IKEY, streamingItem.getLiveLatencyValue());

            i.putExtra(Constants.FORCE_MSS_UPDATE_MANIFEST_ZKEY, streamingItem.isForceMSSUpdateManifest());

            if (null != streamingItem.getThumbnailsZipUrl()) {

                i.putExtra(Constants.EXT_THUMBNAILS_ZIP_URL_INTENT_SKEY, streamingItem.getThumbnailsZipUrl());
            }
            if (null != streamingItem.getChromeCastAlternateUrl()) {
                i.putExtra(Constants.CCAST_ALTERNATE_URL_KEY, streamingItem.getChromeCastAlternateUrl());
            }
            if (null != streamingItem.getChromeCastAlternateDrmAgentType()) {
                i.putExtra(Constants.CCAST_ALTERNATE_DRM_KEY, streamingItem.getChromeCastAlternateDrmAgentType());
            }
            if (null != streamingItem.getChromeCastAlternateDrmLicenserUrl()) {
                i.putExtra(Constants.CCAST_ALTERNATE_DRM_LICENSER_URL_KEY, streamingItem.getChromeCastAlternateDrmLicenserUrl());
            }
            if (null != streamingItem.getChromeCastAlternateDrmCustomData()) {
                i.putExtra(Constants.CCAST_ALTERNATE_DRM_CUSTOM_DATA_KEY, streamingItem.getChromeCastAlternateDrmCustomData());
            }
            if (null != streamingItem.getChromeCastAlternateDrmCookie()) {
                i.putExtra(Constants.CCAST_ALTERNATE_DRM_COOKIE_KEY, streamingItem.getChromeCastAlternateDrmCookie());
            }
            if (null != streamingItem.getStoredName()) {
                i.putExtra(Constants.STORED_NAME_KEY, streamingItem.getStoredName());
            }
            if (null != streamingItem.getScrubbingOptionServer()) {
                i.putExtra(Constants.SCRUBBING_OPTION_SERVER, streamingItem.getScrubbingOptionServer());
            }
            if (null != streamingItem.getScrubbingOptionAsset()) {
                i.putExtra(Constants.SCRUBBING_OPTION_ASSET, streamingItem.getScrubbingOptionAsset());
            }
            if (null != streamingItem.getScrubbingOptionChannel()) {
                i.putExtra(Constants.SCRUBBING_OPTION_CHANNEL, streamingItem.getScrubbingOptionChannel());
            }
            if (null != streamingItem.getScrubbingOptionServiceType()) {
                i.putExtra(Constants.SCRUBBING_OPTION_SERVICE_TYPE, streamingItem.getScrubbingOptionServiceType());
            }
            if (null != streamingItem.getScrubbingOptionStart()) {
                i.putExtra(Constants.SCRUBBING_OPTION_START, streamingItem.getScrubbingOptionStart());
            }
            if (null != streamingItem.getScrubbingOptionEnd()) {
                i.putExtra(Constants.SCRUBBING_OPTION_END, streamingItem.getScrubbingOptionEnd());
            }
            if (null != streamingItem.getScrubbingOptionSpriteResolution()) {
                i.putExtra(Constants.SCRUBBING_OPTION_SPRITE_RESOLUTION, streamingItem.getScrubbingOptionSpriteResolution());
            }
            if (null != streamingItem.getScrubbingOptionSpriteColums()) {
                i.putExtra(Constants.SCRUBBING_OPTION_SPRITE_COLUMS, streamingItem.getScrubbingOptionSpriteColums());
            }
            if (null != streamingItem.getScrubbingOptionSpriteLines()) {
                i.putExtra(Constants.SCRUBBING_OPTION_SPRITE_LINES, streamingItem.getScrubbingOptionSpriteLines());
            }
            if (null != streamingItem.getScrubbingOptionSpriteInterval()) {
                i.putExtra(Constants.SCRUBBING_OPTION_SPRITE_INTERVAL, streamingItem.getScrubbingOptionSpriteInterval());
            }
        } else if (MediaItem.MediaType.MEDIA_PLAYLIST == type) {

            StreamingMediaList streamingList = (StreamingMediaList) mediaItem;
            byte[] playlist = streamingList.serialize();
            if (null != playlist) {
                i.putExtra(Constants.PLAYLIST_KEY, playlist);
            }
        }
        i.setData(mediaUri);
    }

    /**
     * Convert an SSL type into an int to correspond to structure in stack http
     *
     * @param type SSL type
     * @return integer
     */
    public static int getIntValueForSSLType(String type) {
        if (type == null) return Constants.SSL_TYPE_UNKNOWN;
        if (type.equalsIgnoreCase("SSLTypePEM")) {
            return Constants.SSL_TYPE_PEM;
        } else if (type.equalsIgnoreCase("SSLTypeDER")) {
            return Constants.SSL_TYPE_DER;
        } else if (type.equalsIgnoreCase("SSLTypeENG")) {
            return Constants.SSL_TYPE_ENG;
        } else {
            return Constants.SSL_TYPE_UNKNOWN;
        }
    }

    public static String getFileLowerCaseExtension(String filePath) throws Exception {

        int lastDotInPath = filePath.lastIndexOf(".");
        if (lastDotInPath > 0) {
            String extension = filePath.substring(lastDotInPath + 1);
            return extension.toLowerCase();
        } else {
            throw new Exception("impossible to find extension");
        }
    }


    public static String getMD5Hash(String s) {
        try {
            // Create MD5 Hash
            MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
            digest.update(s.getBytes());
            byte messageDigest[] = digest.digest();

            // Create Hex String
            StringBuffer hexString = new StringBuffer();
            for (int i = 0; i < messageDigest.length; i++) {
                String h = Integer.toHexString(0xFF & messageDigest[i]);
                while (h.length() < 2) h = "0" + h;
                hexString.append(h);
            }
            return hexString.toString();

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

    /* Return the path part from a full path */
    public static String getFileParentFolderFromPath(String path) {
        if (path != null) {
            int seperatorPos = path.lastIndexOf("/");
            return path.substring(0, seperatorPos + 1);
        }
        return null;
    }


    /**
     * Returns the filesystem path of a media, given its Uri in the MediaStore
     *
     * @param activity
     * @param contentUri Uri of the content as given by the media store
     * @return absolute filesystem path of the file pointed by the Uri
     */
    public static String getRealPathFromURI(Activity activity, Uri contentUri) {

        // can post image
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor cursor = activity.managedQuery(contentUri,
                proj,    // Which columns to return
                null,    // WHERE clause; which rows to return (all rows)
                null,    // WHERE clause selection arguments (none)
                null);    // Order-by clause (ascending by name)
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();

        return cursor.getString(column_index);
    }


    public static boolean isStringInList(String string, String[] list) {
        if (null == string || null == list) {
            return false;
        }
        for (String test : list) {
            if (string.equals(test)) {
                return true;
            }
        }
        return false;
    }

    /**
     * Returns a ByteBuffer containing all the content of the file given as input
     *
     * @param filePath input file path
     * @return ByteBuffer with the file content
     */
    public static ByteBuffer fileToByteBuffer(String filePath) {
        try {
            FileInputStream inStream = new FileInputStream(filePath);
            File file = new File(filePath);
            int bufferSize = (int) file.length();
            byte[] buffer = new byte[bufferSize];
            ByteArrayOutputStream outStream = new ByteArrayOutputStream(bufferSize);
            int read;
            while (true) {
                read = inStream.read(buffer);
                if (read == -1)
                    break;
                outStream.write(buffer, 0, read);
            }
            ByteBuffer byteData = ByteBuffer.wrap(outStream.toByteArray());
            inStream.close();
            return byteData;
        } catch (Exception e) {
            return null;
        }
    }
}
