package com.cygnusa.hyperm;

import android.annotation.SuppressLint;
import android.content.pm.ActivityInfo;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.StrictMode;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import com.cygnusa.hyperm.util.ApiService;
import com.cygnusa.hyperm.util.GlobalData;
import com.cygnusa.hyperm.util.MainApplication;
import com.cygnusa.hyperm.videoview.UniversalMediaController;
import com.cygnusa.hyperm.videoview.UniversalVideoView;
import com.cygnusa.hyperm.wrappers.MyTopic;
import com.cygnusa.hyperm.wrappers.ProductVideos;
import com.cygnusa.hyperm.wrappers.TrainingCategory;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Calendar;
import java.util.Objects;

import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;


public class ProductVideoViewActivity extends AppCompatActivity {
    public static final String HASH_ALGORITHM = "SHA-256";
    public static ProductVideos CONTENT = new ProductVideos();
    public static MyTopic TOPIC = new MyTopic();
    public static TrainingCategory TRAINING_ID;
    public static String tempfilename = "temp";
    public static ProductVideos content = new ProductVideos();
    public int total;
    public String encryptKey = "Hyperm";
    public File decryptFile = null;
    TextView title;
    UniversalVideoView videoView;
    UniversalMediaController mMediaController;
    View mVideoLayout;
    View appBarLayout;
    Toolbar toolbar;
    ApiService restService;
    ProgressBar progressBar;
    String type;
    Handler handler = new Handler();
    Calendar c;
    private int mSeekPosition;
    private int cachedHeight;
    private boolean isFullscreenMode;
    private boolean isFirst = true;

    public static SecretKeySpec generateKey(final String password) throws NoSuchAlgorithmException {
        final MessageDigest digest = MessageDigest.getInstance(HASH_ALGORITHM);
        byte[] bytes = password.getBytes(StandardCharsets.UTF_8);
        digest.update(bytes, 0, bytes.length);
        byte[] key = digest.digest();
        return new SecretKeySpec(key, "AES");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_video_view);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        setupWindowAnimations();
        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            type = extras.getString("type");
        }
        restService = ((MainApplication) getApplication()).getClient();

        File f = new File(Objects.requireNonNull(getApplicationContext()).getExternalFilesDir(null), ".HYPERM");
        if (!f.exists()) {
            f.mkdirs();
        }

        File f1 = new File(Objects.requireNonNull(getApplicationContext()).getExternalFilesDir(null) + "/" + ".HYPERM", "VIDEO");
        if (!f1.exists()) {
            f1.mkdirs();
        }
        mVideoLayout = findViewById(R.id.video_layout);
        appBarLayout = findViewById(R.id.appBarLayout);
        mMediaController = findViewById(R.id.media_controller);

        title = findViewById(R.id.title);
        videoView = findViewById(R.id.videoView);
        mVideoLayout = findViewById(R.id.video_layout);
        progressBar = findViewById(R.id.progressBar);
        progressBar.setVisibility(View.VISIBLE);

        title.setText(CONTENT.getTitle());
        title.setSelected(true);
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);

        toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        toolbar.setContentInsetStartWithNavigation(0);
        toolbar.setTitle("");
        Objects.requireNonNull(getSupportActionBar()).setTitle("");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        @SuppressLint("PrivateResource")
        Drawable backArrow = getResources().getDrawable(R.drawable.abc_ic_ab_back_material);
        backArrow.setColorFilter(getResources().getColor(R.color.white), PorterDuff.Mode.SRC_ATOP);
        getSupportActionBar().setHomeAsUpIndicator(backArrow);

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                loadContentFile();
            }
        }, 1000);
    }

    public void decrypt(String pathstr, Runnable runnable) throws IOException, NoSuchAlgorithmException,
            NoSuchPaddingException, InvalidKeyException {

        FileInputStream fis = new FileInputStream(pathstr);
        decryptFile = File.createTempFile(tempfilename, ".mp4", this.getCacheDir());
        FileOutputStream fos = new FileOutputStream(decryptFile);
        SecretKeySpec sks = generateKey(encryptKey);
        @SuppressLint("GetInstance")
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, sks);
        CipherInputStream cis = new CipherInputStream(fis, cipher);
        int b;
        byte[] d = new byte[1024];
        while ((b = cis.read(d)) != -1) {
            fos.write(d, 0, b);
        }
        fos.flush();
        fos.close();
        cis.close();
        runnable.run();
    }


    public void loadContentFile() {
        try {
            title.setText(CONTENT.getTitle());
            mVideoLayout.post(new Runnable() {
                @Override
                public void run() {
                    int width = mVideoLayout.getWidth();
                    cachedHeight = (int) (width * 405f / 720f);
                    ViewGroup.LayoutParams videoLayoutParams = mVideoLayout.getLayoutParams();
                    videoLayoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
                    videoLayoutParams.height = cachedHeight;
                    mVideoLayout.setLayoutParams(videoLayoutParams);
                    String fileName = Objects.requireNonNull(getApplicationContext()).getExternalFilesDir(null)
                            + "/" + ".HYPERM/VIDEO/" + CONTENT.getContentid() + "_" + CONTENT.getVersion() + ".mp4";
                    if (new File(fileName).exists()) {
                        // saveTopicData();
                        try {
                            decrypt(fileName, new Runnable() {
                                @Override
                                public void run() {
                                    if (decryptFile != null) {
                                        try {
                                            Uri videoUri = Uri.parse(decryptFile.getAbsolutePath());
                                            videoView.setVideoURI(videoUri);
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                    }
                                }
                            });
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else {
                        videoView.setVideoPath(CONTENT.getFile_url().trim());
                    }

                    videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                        @Override
                        public void onPrepared(MediaPlayer mp) {
                            if (isFirst) {
                                isFirst = false;
                                videoView.requestFocus();
                                videoView.start();
                            } else {
                                videoView.seekTo(1000);
                                mMediaController.showComplete();
                            }
                        }
                    });

                    videoView.setMediaController(mMediaController);
                    videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                        @Override
                        public void onCompletion(MediaPlayer mp) {
                            try {
                                String mName = Objects.requireNonNull(getApplicationContext()).getExternalFilesDir(null)
                                        + "/" + ".HYPERM/VIDEO/" + CONTENT.getContentid() + "_" + CONTENT.getVersion() + ".mp4";
                                videoView.closePlayer();
                                if (new File(mName).exists()) {
                                    decrypt(mName, new Runnable() {
                                        @Override
                                        public void run() {
                                            if (decryptFile != null) {
                                                try {
                                                    Uri videoUri = Uri.parse(decryptFile.getAbsolutePath());
                                                    videoView.setVideoURI(videoUri);
                                                } catch (Exception e) {
                                                    e.printStackTrace();
                                                }
                                            }
                                        }
                                    });
                                } else {
                                    videoView.setVideoPath(CONTENT.getFile_url().trim());
                                }

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

                    videoView.setVideoViewCallback(new UniversalVideoView.VideoViewCallback() {
                        @Override
                        public void onScaleChange(boolean isFullscreen) {
                            isFullscreenMode = isFullscreen;
                            if (isFullscreen) {
                                ViewGroup.LayoutParams layoutParams = mVideoLayout.getLayoutParams();
                                layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
                                layoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT;
                                mVideoLayout.setLayoutParams(layoutParams);

                            } else {
                                ViewGroup.LayoutParams layoutParams = mVideoLayout.getLayoutParams();
                                layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
                                layoutParams.height = cachedHeight;
                                mVideoLayout.setLayoutParams(layoutParams);

                            }
                            switchTitleBar(!isFullscreen);
                        }

                        @Override
                        public void onPause(MediaPlayer mediaPlayer) {
                            if (videoView != null && videoView.isPlaying()) {
                                mSeekPosition = videoView.getCurrentPosition();
                                videoView.pause();
                            }
                        }

                        @Override
                        public void onStart(MediaPlayer mediaPlayer) {
                            progressBar.setVisibility(View.GONE);

                        }

                        @Override
                        public void onBufferingStart(MediaPlayer mediaPlayer) {
                            progressBar.setVisibility(View.GONE);
                        }

                        @Override
                        public void onBufferingEnd(MediaPlayer mediaPlayer) {

                        }

                    });
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            progressBar.setVisibility(View.GONE);
        }
    }

    private void switchTitleBar(boolean show) {
        androidx.appcompat.app.ActionBar supportActionBar = getSupportActionBar();
        if (supportActionBar != null) {
            if (show) {
                supportActionBar.show();
            } else {
                supportActionBar.hide();
            }
        }
    }

    private void setupWindowAnimations() {
        this.overridePendingTransition(R.anim.animation_enter,
                R.anim.animation_leave);
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            this.overridePendingTransition(R.anim.animation_f_enter,
                    R.anim.animation_f_leave);
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        if (isFullscreenMode) {
            videoView.setFullscreen(false);
        } else {
            super.onBackPressed();
            this.overridePendingTransition(R.anim.animation_f_enter,
                    R.anim.animation_f_leave);
        }


    }

    @Override
    protected void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("SEEK_POSITION_KEY", mSeekPosition);
    }

    @Override
    protected void onRestoreInstanceState(Bundle outState) {
        super.onRestoreInstanceState(outState);
        mSeekPosition = outState.getInt("SEEK_POSITION_KEY");
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (GlobalData.canLogout) {
            finish();
        }
    }
}