/**
 * $URL$
 * DAAND
 * Copyright (C) 2004 - 2013, INSIDE Secure BV.  All rights reserved.
 */
package com.insidesecure.drm.android.reference.activities;

import android.Manifest;
import android.app.*;
import android.content.*;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.net.Uri;
import android.os.*;
import android.util.Log;
import android.view.*;

import android.widget.TextView;
import android.widget.Toast;
import com.insidesecure.drm.android.reference.*;
import com.insidesecure.drm.android.reference.xoplayer.R;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

public class LauncherActivity extends Activity
{
    public static final int WARNING_NATIVE_PLAYER_ON_BAD_SDK_LEVEL = 1;
    public static final String EXTRA_NEW_CDESC = "extra_new_cdesc";

    private static final String[] APP_PERMISSIONS = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
    private static final int APP_PERMISSIONS_REQUEST_CODE = 4;

    private static final String TAG = "LauncherActivity";

    private static final boolean mShowEula = false;
    private static boolean mEulaAccepted = false;

    private SharedPreferences mPreferences;
    private boolean mPermissionsGranted;
    private Thread mEulaLoaderThread;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.launcher);

        if (Build.VERSION.SDK_INT < 23 || checkPermissions())
        {
            mPermissionsGranted = true;
            runEulaLoaderThread();
        }
        else
        {
            requestPermissions(APP_PERMISSIONS, APP_PERMISSIONS_REQUEST_CODE);
        }

    }

    private void runEulaLoaderThread()
    {
        final TextView text = (TextView) findViewById(R.id.init_messages);
        String formatted = String.format("%s v%s", getText(R.string.dialog_title), DRMAgentDelegate.getDRMAgentVersionInfo().getAPIVersion());
        text.setText(formatted);

        mEulaLoaderThread = new Thread(
                new Runnable()
                {
                    public void run()
                    {
                        Log.i(TAG, "SHOW_EULA=" + mShowEula);
                        mPreferences = getSharedPreferences(Constants.PREFERENCES_FILENAME, Context.MODE_PRIVATE);
                        //check flag "eula accepted"
                        mEulaAccepted = mPreferences.getBoolean(Constants.PREFERENCES_EULA_ACCEPTED, false);
                    }
                }
        );
        mEulaLoaderThread.start();
    }

    private void loadCDescIfNeeded(ContentHandler.OnCDescRetrieveFinishedCallback callback)
    {
        Intent intent = getIntent();
        Uri uri = intent.getData();
        if(uri != null)
        {
            ContentHandler.addCustomContent(Uri.parse(uri.toString()), callback);
        }
        else
        {
            callback.onRetrieveFinished(null);
        }
    }

    private boolean checkPermissions()
    {
        for (int i = 0; i < APP_PERMISSIONS.length; i++)
        {
            if (!(checkSelfPermission(APP_PERMISSIONS[i]) == PackageManager.PERMISSION_GRANTED))
            {
                return false;
            }
        }
        return true;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults)
    {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == APP_PERMISSIONS_REQUEST_CODE)
        {
            boolean isGranted = true;
            for (int i = 0; i < grantResults.length; i++)
            {
                if (grantResults[i] == PackageManager.PERMISSION_DENIED)
                {
                    isGranted = false;
                    Toast.makeText(this,"Permission denied, cannot continue",Toast.LENGTH_LONG).show();
                    finish();
                    break;
                }
            }
            if (isGranted)
            {
                mPermissionsGranted = true;
                runEulaLoaderThread();
            }
        }
    }

    private void copyEULA()
    {
        final AssetManager assetManager = this.getAssets();
        String eulaFile = "eula-2013-02-21.htm";

        try
        {
            FileOutputStream outputStream = null;
            InputStream inputStream = null;
            try
            {
                inputStream = assetManager.open("eula/" + eulaFile);
                outputStream = new FileOutputStream(Constants.CONFIGURATION_CDESC_PATH + eulaFile);
                Tools.copyStream(inputStream, outputStream);
            }
            catch (Exception e)
            {
                Log.e(TAG, "Error while opening asset: eula/" + eulaFile);
            }
            finally
            {
                if (inputStream != null)
                    inputStream.close();
                if (outputStream != null)
                {
                    outputStream.flush();
                    outputStream.close();
                }
            }
        }
        catch (Exception e)
        {
            Log.e(TAG,"Error while listing assets: " + e.getMessage(),e);
        }
    }

    @Override
    protected void onResume()
    {
        if (mPermissionsGranted)
        {
            try
            {
                mEulaLoaderThread.join();

                if (mShowEula)
                {
                    if (mEulaAccepted)
                    {
                        Log.d(TAG, "Just go ahead with initialization.");
                        initialization();
                    }
                    else
                    {
                        copyEULA();

                        Log.d(TAG, "Displaying EULA!");
                        Intent intent = new Intent(getBaseContext(), EulaActivity.class);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
                        startActivityForResult(intent, 0);
                    }
                }
                else
                {
                    initialization();
                }
            }
            catch (InterruptedException e)
            {
                Log.e(TAG, "Error while waiting for thread to complete: " + e.getMessage(), e);
                throw new RuntimeException("Error while waiting for thread to complete: " + e.getMessage());
            }
        }
        super.onPostResume();
    }

    @Override
    protected void onActivityResult(final int requestCode, final int resultCode, final Intent data)
    {
        Log.d(TAG, "Activity result received: " + requestCode + " result: " + resultCode + " intent: " + data);

        if(resultCode==1)
        {
            mEulaAccepted = true;
            initialization();
        }
    }

    private void initialization()
    {
        if (Build.VERSION.SDK_INT < 14 && !DRMFusionAgentReferenceApplication.sSupportOldAndroidVersions)
        {
            showDialog(WARNING_NATIVE_PLAYER_ON_BAD_SDK_LEVEL);
        }
        else
        {
            goForIt();
        }
    }


    private void goForIt()
    {
        final View id = this.findViewById(R.id.launcher);

        final Handler handler = new Handler(Looper.myLooper());

        loadCDescIfNeeded(new ContentHandler.OnCDescRetrieveFinishedCallback()
        {
            public void onRetrieveFinished(final String loadedFilePath)
            {
                final Runnable runnable = new Runnable()
                {
                    public void run()
                    {
                        Intent intent = new Intent(getBaseContext(), DRMFusionAgentReferenceApplication.sHomeActivityClass);

                        if(loadedFilePath != null && new File(loadedFilePath).exists())
                        {
                            intent.putExtra(EXTRA_NEW_CDESC, loadedFilePath);
                        }
                        startActivity(intent);
                        finish();

                    }
                };
                handler.postDelayed(runnable, 1000);

                id.setOnClickListener(new View.OnClickListener()
                {
                    public void onClick(final View view)
                    {
                        handler.removeCallbacks(runnable);
                        startActivity(new Intent(getBaseContext(), DRMFusionAgentReferenceApplication.sHomeActivityClass));
                        finish();
                    }
                });
                id.setClickable(true);
            }

            public void onRetrieveFailed(final String errorMessage)
            {
                LauncherActivity.this.runOnUiThread(new Runnable()
                {
                    public void run()
                    {
                        Toast.makeText(LauncherActivity.this, errorMessage, Toast.LENGTH_SHORT).show();
                    }
                });
            }

        });

    }

    @Override
    protected Dialog onCreateDialog(int id)
    {
        Dialog dialog;
        switch (id)
        {
            case WARNING_NATIVE_PLAYER_ON_BAD_SDK_LEVEL:
                final DialogInterface.OnClickListener positiveListener = new DialogInterface.OnClickListener()
                {
                    public void onClick(DialogInterface dialog, int id)
                    {
                        dialog.cancel();
                        goForIt();
                    }
                };
                return Tools.createAlertDialog(this, getText(R.string.dialog_title), getText(R.string.wrong_sdk_level_for_native), false, getText(R.string.dialog_button_ok), positiveListener, null, null);
            default:
                throw new RuntimeException("Unhandled ID: " + id);
        }
    }

}
