package com.example.camara.DonControl;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.AnimationDrawable;
import android.hardware.display.DisplayManager;
import android.hardware.display.VirtualDisplay;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.media.MediaScannerConnection;
import android.media.projection.MediaProjection;
import android.media.projection.MediaProjectionManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.SparseIntArray;
import android.view.Surface;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.ToggleButton;

import java.io.File;
import java.io.IOException;

public class Principal extends AppCompatActivity {

//--------------------------verify state if  exists external memory----------------------------**
    final String state = Environment.getExternalStorageState();

    //------------------------------------grabadora y reproductor
    boolean grabando;
    MediaRecorder grabadora;
    MediaPlayer reproductor;
    Button botonR;
    Button botonG;

    //-----------------------------------tomar fotos y cargar imagenes.
    String path;
    ImageView imagen;
    Button botonCam;
    private final String CARPETA_RAIZ = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "DonControlApp/";
    private final String RUTA_IMAGEN = CARPETA_RAIZ + "FotosDC";
    private final String RUTA_VIDEO = CARPETA_RAIZ + "videosDC";
    final int COD_SELECCIONA = 1;
    final int COD_CAPTURA = 2;
    int MY_PERMISSIONS_REQUEST_CAMERA=0;

    //---------------------------------------------Animation-----
    ImageView cuadroDC;
    AnimationDrawable animacionDC;

    Button botonShare;

    //-----------------------------------------------RecVideo*****
    ToggleButton btnVideo;
    private static final String TAG = "MainActivity";
    private static final int REQUEST_CODE = 1000;
    private int mScreenDensity;
    private MediaProjectionManager mProjectionManager;
    private static final int DISPLAY_WIDTH = 1280;
    private static final int DISPLAY_HEIGHT = 720;
    private MediaProjection mMediaProjection;
    private VirtualDisplay mVirtualDisplay;
    private MediaProjectionCallback mMediaProjectionCallback;
    protected ToggleButton mToggleButton ;
    private MediaRecorder mMediaRecorder;
    private static final SparseIntArray ORIENTATIONS = new SparseIntArray();
    private static final int REQUEST_PERMISSIONS = 10;

    static {
        ORIENTATIONS.append(Surface.ROTATION_0, 90);
        ORIENTATIONS.append(Surface.ROTATION_90, 0);
        ORIENTATIONS.append(Surface.ROTATION_180, 270);
        ORIENTATIONS.append(Surface.ROTATION_270, 180);
    }

    //------------------------------------------------Bitmap-------------**
//    BitmapFactory.Options options = new BitmapFactory.Options();
//    options.inJustDecodeBounds = true;
//    BitmapFactory.decodeResource(getResources(),R.id.don_control, Options);
//    int imageHeight = options.outHeight;
//    int imageWidth = options.outWidth;
//    String imageType = options.outMimeType;

    //................................................onCreate...................................................\\
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_principal);

        //-------------------------------------------------------------grabar botoón
        grabando = false;
        botonG = (Button) findViewById(R.id.btnRec);

        //----------------------------------------------------------------------reproducir Botón
        botonR = (Button) findViewById(R.id.btnPlay);

        //--------------------------------------------------------------------------camara e imageView
        imagen = (ImageView) findViewById(R.id.caliImg);
        botonCam = (Button) findViewById(R.id.btnCam);

        //compartir
        botonShare = (Button) findViewById(R.id.btnShare);

        //cuadro animcion-------------------------------------------------------cuadro animacion reproduce.
        cuadroDC = (ImageView) findViewById(R.id.don_control);
        cuadroDC.setImageResource(0);
        // set the xml with images
        cuadroDC.setBackgroundResource(R.drawable.don_control_anim);
        // get the background to show the animation
        animacionDC = (AnimationDrawable) cuadroDC.getBackground();

        //--------------------------------------------------------------RecVideo------**

        btnVideo = (ToggleButton) findViewById(R.id.btnGuardar);
        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        mScreenDensity = metrics.densityDpi;

        mMediaRecorder = new MediaRecorder();

        mProjectionManager = (MediaProjectionManager) getSystemService
                (Context.MEDIA_PROJECTION_SERVICE);

        //-------------------------------------------Definir Orientacion de la pantalla . Horizontal
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);

//-------------------------------------------------------------------metodos y funciones-------------------------------------------------------------------------------------------------//

            botonG.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

//                       escuchaDC.start();

                        if (grabando) {
                            grabando = false;
                            grabadora.stop();
                            grabadora.release();
                            botonR.setEnabled(true);
                        } else {
                            botonR.setEnabled(false);
                            grabadora = new MediaRecorder();
                            animacionDC.stop();
                            try {
                                grabadora.reset();
                                grabadora.setAudioSource(MediaRecorder.AudioSource.MIC);
                                grabadora.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
                                grabadora.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
                                grabadora.setOutputFile("sdcard/DonControlApp/test.3gp");
                                grabadora.prepare();
                                grabadora.start();
                                grabando = true;

                            } catch (IllegalStateException | IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }

            });
            botonR.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    reproducir("sdcard/DonControlApp/test.3gp");

                }
            });

            botonCam.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    CargarImagen();
                }
            });

            botonShare.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    compartir();
                }
            });

            btnVideo.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    if (ContextCompat.checkSelfPermission(Principal.this,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE) + ContextCompat
                            .checkSelfPermission(Principal.this,
                                    Manifest.permission.RECORD_AUDIO)
                            != PackageManager.PERMISSION_GRANTED) {
                        if (ActivityCompat.shouldShowRequestPermissionRationale
                                (Principal.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) ||
                                ActivityCompat.shouldShowRequestPermissionRationale
                                        (Principal.this, Manifest.permission.RECORD_AUDIO)) {
                            mToggleButton.setChecked(false);

                        } else {
                            ActivityCompat.requestPermissions(Principal.this,
                                    new String[]{Manifest.permission
                                            .WRITE_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO},
                                    REQUEST_PERMISSIONS);
                        }
                    } else {
                        onToggleScreenShare(view);
                    }
                }
            });
        }

        protected void onPause(){
        super.onPause();
        }

        protected void onStop(){
        super.onStop();
        //Toast.makeText(getApplicationContext(), "La aplicación se ha minimizado",  Toast.LENGTH_LONG).show();
        }

    //-------------------------------------------------------------Reproducir Animacion Y Audio-------------*

    private void reproducir(String path) {

        reproductor = new MediaPlayer();
        animacionDC.start();

        Log.d("MOSTRAR DO WHILE","INICIO LA ANIMACION");
        try {
            reproductor.setDataSource(path);
            reproductor.prepare();
            reproductor.start();

            if (animacionDC.isRunning()) {
                do {
                    reproductor.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                        @Override
                        public void onCompletion(MediaPlayer mp) {
                            if (!mp.isLooping())
                                animacionDC.stop();
                                cuadroDC.setBackgroundResource(0);
                                cuadroDC.setBackgroundResource(R.drawable.don_control_anim);
                                animacionDC = (AnimationDrawable) cuadroDC.getBackground();

                        }
                    });

                    Log.d("MOSTRAR DO WHILE","SE DETUVO LA ANIMACION");
                }while (reproductor.isLooping());
            }

        } catch (IllegalArgumentException | SecurityException | IllegalStateException | IOException e) {
            e.printStackTrace();
        }
    }

    //---------------------------------------------------imagen y capturar foto
    private void CargarImagen() {

//        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
//                == PackageManager.PERMISSION_DENIED)

            ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.CAMERA}, MY_PERMISSIONS_REQUEST_CAMERA);

        final CharSequence[] opciones = {"Tomar Foto", "Cargar Imagen", "Cancelar"};
        final AlertDialog.Builder alertOpciones = new AlertDialog.Builder(Principal.this);
        alertOpciones.setTitle("Seleccione una Opción");
        alertOpciones.setItems(opciones, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                if (opciones[i].equals("Tomar Foto")) {

                    takePic();

                } else {
                    if (opciones[i].equals("Cargar Imagen")) {

                        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                        intent.setType("image/");
                        startActivityForResult(Intent.createChooser(intent, "Seleccione la Aplicación"), COD_SELECCIONA);

                    } else {
                        dialogInterface.dismiss();
                    }
                }
            }
        });
        alertOpciones.show();
    }

    private void takePic() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                == PackageManager.PERMISSION_DENIED)

            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA},
                    MY_PERMISSIONS_REQUEST_CAMERA);

            if (Environment.MEDIA_MOUNTED.equals(state)) {
                File fileImagen = new File(Environment.getExternalStorageDirectory(), RUTA_IMAGEN);
                boolean isCreated = fileImagen.exists();
                String nombreImagen = "";

                if (!isCreated) {
                    isCreated = fileImagen.mkdirs();

                }
                if (isCreated) {
                    nombreImagen = "DonCcontrol_" + (System.currentTimeMillis() / 100) + ".jpg";
                }

                path = Environment.getExternalStorageDirectory()
                        + File.separator + RUTA_IMAGEN + File.separator + nombreImagen;

                //path = "//misImagenesPrueba/misFotos/22/02/2018125745.jpg"

                File imagen = new File(path);

                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(imagen));

                startActivityForResult(intent, COD_CAPTURA);

            }
    }
    //-------------------------------------compartir
    private void compartir() {

        Intent compartir = new Intent(android.content.Intent.ACTION_SEND);
        compartir.putExtra(Intent.ACTION_PICK, MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
        compartir.setType("video/");
        startActivity(Intent.createChooser(compartir, "Compartir vía"));
    }


    //--------------------------------------------CaprturaVideo---***

    public void onToggleScreenShare(View view) {

        if (((ToggleButton) view).isChecked()) {
            initRecorder();
            shareScren();
            reproducir("sdcard/DonControlApp/test.3gp");

        } else {
            mMediaRecorder.stop();
            mMediaRecorder.reset();
            reproductor.stop();
            animacionDC.stop();
            cuadroDC.setBackgroundResource(0);
            cuadroDC.setBackgroundResource(R.drawable.don_control_anim);
            animacionDC = (AnimationDrawable) cuadroDC.getBackground();
            Log.v(TAG, "Stopping Recording");
            stopScreenSharing();
            Toast.makeText(getApplicationContext(), "El video se h guardado en:" + RUTA_VIDEO, Toast.LENGTH_LONG).show();
        }
    }

    private void shareScren(){
        if (mMediaProjection == null) {
            startActivityForResult(mProjectionManager.createScreenCaptureIntent(), REQUEST_CODE);
            return;
        }else
        mVirtualDisplay = createVirtualDisplay();
        mMediaRecorder.start();
    }

    private VirtualDisplay createVirtualDisplay(){
        return mMediaProjection.createVirtualDisplay("Principal",
                DISPLAY_WIDTH, DISPLAY_HEIGHT, mScreenDensity,
                DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
                mMediaRecorder.getSurface(), null/*Callbakcs*/,null/*Handler*/);
    }

    private void initRecorder(){
        String nombreVideo = "DonCcontrol_" + (System.currentTimeMillis() / 2000) + ".mp4";
        File fileVideo = new File(Environment.getExternalStorageDirectory(), RUTA_VIDEO);
//        path = Environment.getExternalStorageDirectory()
//                + File.separator + RUTA_VIDEO + File.separator +  nombreVideo;

        try{
            mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
            mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
            mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
            mMediaRecorder.setOutputFile(fileVideo + nombreVideo);
//            mMediaRecorder.setOutputFile(path);
            mMediaRecorder.setVideoSize(DISPLAY_WIDTH, DISPLAY_HEIGHT);
            mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
            mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
            mMediaRecorder.setVideoEncodingBitRate(512 * 1000);
            mMediaRecorder.setVideoFrameRate(30);
            int rotation = getWindowManager().getDefaultDisplay().getRotation();
            int orientation = ORIENTATIONS.get(rotation + 90);
            mMediaRecorder.setOrientationHint(orientation);
            mMediaRecorder.prepare();

        }catch(IOException e){
            e.printStackTrace();
        }

    }

    private class MediaProjectionCallback extends MediaProjection.Callback {
        @Override
        public void onStop(){

            if (mToggleButton.isChecked()){
                mToggleButton.setChecked(false);
                mMediaRecorder.stop();
                mMediaRecorder.reset();
                Log.v(TAG, "Recording Stopped");

            }
            mMediaProjection = null;
            stopScreenSharing();
        }

    }

    private void stopScreenSharing(){
        if(mVirtualDisplay == null){
            return;
        }
        mVirtualDisplay.release();
        //mMediaRecorder.release(); //If used: mMediaRecorder object cannot
        // be reused again
        destroyMediaProjection();
    }

    @Override
    public void onDestroy(){
        super.onDestroy();
        destroyMediaProjection();
    }

    private void destroyMediaProjection(){
        if (mMediaProjection != null){
            mMediaProjection.unregisterCallback(mMediaProjectionCallback);
            mMediaProjection.stop();
            mMediaProjection = null;
        }
        Log.i(TAG, "MediaProjection Stopped");
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String permissions[],
                                           @NonNull int[] grantResults) {
        switch (requestCode) {
            case REQUEST_PERMISSIONS: {
                if ((grantResults.length > 0) && (grantResults[0] +
                        grantResults[1]) == PackageManager.PERMISSION_GRANTED) {
                    onToggleScreenShare(mToggleButton);
                } else {
                    mToggleButton.setChecked(false);
                }
            }
        }
    }

//--------------------------------------------------------------onActivityResult de la funcion camara e imagenes---------------------------------------------------☻\\

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {

            switch (requestCode) {
                case COD_SELECCIONA:
                    Uri pathSelec = data.getData();
                    imagen.setImageURI(pathSelec);
                    break;

                case COD_CAPTURA:
                    MediaScannerConnection.scanFile(this, new String[]{path}, null,
                            new MediaScannerConnection.OnScanCompletedListener() {
                                public void onScanCompleted(String s, Uri uri) {
                                    Log.i("Ruta de almacenamiento", "Path: " + path);
                                }
                            });

                    Bitmap bitmap = BitmapFactory.decodeFile(path);
                    imagen.setImageBitmap(bitmap);
                    Toast.makeText(getApplicationContext(), "La captura se guardó en :" + path, Toast.LENGTH_LONG).show();
                    break;
            }

        }

        if (requestCode != REQUEST_CODE) {
            Log.e(TAG, "Unknown request code: " + requestCode);
            return;
        }
        if (resultCode != RESULT_OK) {
            Toast.makeText(getApplicationContext(),
                    "Screen Cast Permission Denied", Toast.LENGTH_SHORT).show();
            mToggleButton.setChecked(false);
            return;
        }
        mMediaProjectionCallback = new MediaProjectionCallback();
        mMediaProjection = mProjectionManager.getMediaProjection(resultCode, data);
        mMediaProjection.registerCallback(mMediaProjectionCallback, null);
        mVirtualDisplay = createVirtualDisplay();
        mMediaRecorder.start();
    }
}