package com.cygnusa.hyperm;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.StrictMode;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.reflect.TypeToken;
import com.cygnusa.hyperm.util.ApiService;
import com.cygnusa.hyperm.util.GlobalData;
import com.cygnusa.hyperm.util.MainApplication;
import com.cygnusa.hyperm.util.MyCallback;
import com.cygnusa.hyperm.util.StorePreference;
import com.cygnusa.hyperm.util.UtilService;
import com.cygnusa.hyperm.videoview.UniversalMediaController;
import com.cygnusa.hyperm.videoview.UniversalVideoView;
import com.cygnusa.hyperm.wrappers.CommonResponse;
import com.cygnusa.hyperm.wrappers.ContentFile;
import com.cygnusa.hyperm.wrappers.ErrorResponse;
import com.cygnusa.hyperm.wrappers.HitCountModel;
import com.cygnusa.hyperm.wrappers.MyContent;
import com.cygnusa.hyperm.wrappers.MyTopic;
import com.cygnusa.hyperm.wrappers.TrainingCategory;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Objects;

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

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class VideoViewActivity extends AppCompatActivity {
    public static MyContent CONTENT = new MyContent();
    public static MyTopic TOPIC = new MyTopic();
    public static TrainingCategory TRAINING_ID;
    // public static String TRAINING_ID="";
    public int num;
    public int total;
    TextView title, contentTitle, contentDescription, mTextLanguageSelection, txtDownload, txtClear;
    UniversalVideoView videoView;
    UniversalMediaController mMediaController;
    View mBottomLayout;
    View mVideoLayout;
    View appBarLayout;
    ImageView mImageLangSelection, imgDownload, imgClear;
    Toolbar toolbar;
    ApiService restService;
    ProgressBar progressBar;
    URI uri;
    private int mSeekPosition;
    private int cachedHeight;
    private boolean isFullscreenMode;
    private AlertDialog.Builder builder;
    private ProgressDialog pDialog;
    private ContentFile SELECTED_CONTENT = new ContentFile();
    String type;
    private StorePreference storePreference;
    Handler handler = new Handler();
    public static final String HASH_ALGORITHM = "SHA-256";
    public String encryptKey = "Hyperm";
    public File decryptFile = null;
    public static String tempfilename = "temp", formattedDate = "";
    String fromTime, toTime, finalTime;
    Calendar c;
    SimpleDateFormat df;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video_view);
        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);
        mBottomLayout = findViewById(R.id.bottom_layout);
        appBarLayout = findViewById(R.id.appBarLayout);
        mMediaController = findViewById(R.id.media_controller);
        title = findViewById(R.id.title);
        videoView = findViewById(R.id.videoView);
        mTextLanguageSelection = findViewById(R.id.textLanguage);
        mImageLangSelection = findViewById(R.id.imgLanguage);

        txtDownload = findViewById(R.id.downloadText);
        imgDownload = findViewById(R.id.download);

        txtClear = findViewById(R.id.clear);
        imgClear = findViewById(R.id.img_clear);

        txtClear.setAlpha(0.3f);
        imgClear.setAlpha(0.3f);
        txtClear.setEnabled(false);
        imgClear.setEnabled(false);

        mVideoLayout = findViewById(R.id.video_layout);
        progressBar = findViewById(R.id.progressBar);
        progressBar.setVisibility(View.VISIBLE);
        title.setText(CONTENT.getTitle());
        title.setSelected(true);
        contentTitle = findViewById(R.id.contentTitle);
        contentDescription = findViewById(R.id.contentDescription);
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        storePreference = new StorePreference(this);

        getCurrentTime();
        mTextLanguageSelection.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showLanguageSelectionList();
            }
        });
        mImageLangSelection.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mTextLanguageSelection.performClick();
            }
        });

        txtDownload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                downloadVideo();

            }
        });

        imgDownload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                txtDownload.performClick();
            }
        });

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

                new AlertDialog.Builder(VideoViewActivity.this)
                        .setMessage("Are you sure you want to clear?")
                        .setPositiveButton("Yes",
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(
                                            DialogInterface dialog,
                                            int which) {
//
                                        clearFileFromDevice();

                                    }
                                }).setNegativeButton("No", null).show();


            }
        });

        imgClear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                txtClear.performClick();
            }
        });

        toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        toolbar.setContentInsetStartWithNavigation(0);
        toolbar.setTitle("");
        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.btn_bg_color), PorterDuff.Mode.SRC_ATOP);
        getSupportActionBar().setHomeAsUpIndicator(backArrow);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                loadContentFile(getContentFile());
            }
        }, 1000);
    }

    private void getCurrentTime() {
        c = Calendar.getInstance();
        System.out.println("fromTime " + c.getTime());

        df = new SimpleDateFormat("HH:mm:ss");
        fromTime = df.format(c.getTime());
        Log.e("fromTime", fromTime);
    }

    public boolean isFileAlreadyDownload(ContentFile contentFile) {
        String fileName = Objects.requireNonNull(getApplicationContext()).getExternalFilesDir(null)
                + "/" + ".HYPERM/VIDEO/" + CONTENT.getContentid() + "_" + CONTENT.getVersion()
                + "_" + contentFile.getLanguage_code() + ".mp4";
        File f = new File(fileName);
        return f.exists();
    }

    public void clearFileFromDevice() {
        String fileName = Objects.requireNonNull(getApplicationContext()).getExternalFilesDir(null)
                + "/" + ".HYPERM/VIDEO/" + CONTENT.getContentid() + "_" + CONTENT.getVersion()
                + "_" + SELECTED_CONTENT.getLanguage_code() + ".mp4";
        File f = new File(fileName);
        if (f.exists()) {
            f.delete();
            GlobalData.sdb.execSQL("delete from topic_content where" + " category_id='"
                    + TRAINING_ID.getCateid() + "' and topic_id='" + TOPIC.getAssettopicid() + "' and content_id='" + CONTENT.getContentid() + "'");

            Cursor cursor = GlobalData.sdb.rawQuery("select * from topic_content where" + " category_id='"
                    + TRAINING_ID.getCateid() + "' and topic_id='" + TOPIC.getAssettopicid() + "' and content_id='" + CONTENT.getContentid() + "'", null);
            if (cursor.getCount() == 0) {
                GlobalData.sdb.execSQL("delete  from topic where" + " category_id='"
                        + TRAINING_ID.getCateid()
                        + "' and topic_id='" + TOPIC.getAssettopicid() + "'");
            }
            txtDownload.setAlpha(1f);
            imgDownload.setAlpha(1f);
            txtDownload.setEnabled(true);
            imgDownload.setEnabled(true);

            txtClear.setAlpha(0.3f);
            imgClear.setAlpha(0.3f);
            imgClear.setEnabled(false);
            txtClear.setEnabled(false);
            GlobalData.showToast(getBaseContext(), "File deleted from local storage", Toast.LENGTH_SHORT).show();
        }

    }

    private void sendHitCountToServer() {
        restService.sendAllHitCount(buildConfigData()).enqueue(new Callback<CommonResponse>() {
            @Override
            public void onResponse(Call<CommonResponse> call, Response<CommonResponse> response) {
                if (response.body() != null) {
                    Log.e("responeHit", response.body().getMessage());
                } else {
                    Log.e("responeHit", response.body().getMessage());
                }
            }

            @Override
            public void onFailure(Call<CommonResponse> call, Throwable t) {
                if (t.getMessage() != null) {
                    Log.e("responeHit", t.getMessage());
                }
            }
        });
    }

    private HitCountModel buildConfigData() {
        HitCountModel hitCountModel = new HitCountModel();
        hitCountModel.setPage("Learning");
        hitCountModel.setAssettopicid(Integer.valueOf(CONTENT.getAssettopicid()));
        hitCountModel.setContentid(Integer.valueOf(CONTENT.getContentid()));
        hitCountModel.setViewtime(finalTime);
        return hitCountModel;
    }

    @SuppressLint("StaticFieldLeak")
    private void downloadVideo() {
        new AsyncTask<Void, Integer, Void>() {
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                try {
                    pDialog = new ProgressDialog(VideoViewActivity.this);
                    pDialog.setTitle("");
                    pDialog.setMessage("Downloading...");
                    pDialog.setIndeterminate(false);
                    pDialog.setMax(100);
                    pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                    pDialog.setCancelable(false);
                    pDialog.show();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }


            @Override
            protected Void doInBackground(Void... voids) {
                OutputStream output = null;
                InputStream input = null;
                try {
                    int count;
                    URL url = new URL(SELECTED_CONTENT.getFile_url());
                    URLConnection conection = url.openConnection();
                    conection.connect();
                    int lenghtOfFile = conection.getContentLength();
                    input = new BufferedInputStream(url.openStream(),
                            8192);
                    String fileName = Objects.requireNonNull(getApplicationContext()).getExternalFilesDir(null)
                            + "/" + ".HYPERM/VIDEO/" + CONTENT.getContentid() + "_" + CONTENT.getVersion()
                            + "_" + SELECTED_CONTENT.getLanguage_code() + ".mp4";
                    output = new FileOutputStream(fileName);
                    byte data[] = new byte[1024];
                    long total = 0;
                    SecretKeySpec sks = generateKey(encryptKey);
                    @SuppressLint("GetInstance")
                    Cipher cipher = Cipher.getInstance("AES");
                    cipher.init(Cipher.ENCRYPT_MODE, sks);
                    output = new CipherOutputStream(output, cipher);

                    while ((count = input.read(data)) != -1) {
                        num++;
                        total += count;
                        publishProgress((int) (total * 100 / lenghtOfFile));
                        output.write(data, 0, count);
                    }
                    output.flush();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    try {
                        Objects.requireNonNull(output).close();
                        Objects.requireNonNull(input).close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                return null;
            }

            @Override
            protected void onProgressUpdate(Integer... progress) {
                super.onProgressUpdate(progress);
                // Update the ProgressBar
                pDialog.setProgress(progress[0]);
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
                pDialog.dismiss();
             //   GlobalData.showToast(getBaseContext(), "Video saved on local, will sync to server when online", Toast.LENGTH_LONG).show();
                loadContentFile(SELECTED_CONTENT);
            }

        }.execute();

    }

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

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

        FileInputStream fis = new FileInputStream(pathstr);
        String format = ".pdf";
        if (filetype.equalsIgnoreCase("pdf")) {
            format = ".pdf";
        } else if (filetype.equalsIgnoreCase("mp4")) {
            format = ".mp4";
        }
        decryptFile = File.createTempFile(tempfilename, format, this.getCacheDir());
        FileOutputStream fos = new FileOutputStream(decryptFile);
        SecretKeySpec sks = generateKey(encryptKey);
        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 saveTopicData() {

        Cursor cursor = GlobalData.sdb.rawQuery("select * from topic_content where" + " category_id='"
                + TRAINING_ID.getCateid() + "' and topic_id='" + TOPIC.getAssettopicid() + "' and content_id='" + CONTENT.getContentid() + "'", null);
        if (cursor.getCount() == 0) {

            Gson gson = new Gson();
            JsonElement jsonElement = gson.toJsonTree(
                    CONTENT, new TypeToken<MyContent>() {
                    }.getType());
            ContentValues values = new ContentValues();
            values.put("topic_content", jsonElement.toString());
            values.put("category_id", TRAINING_ID.getCateid());
            values.put("topic_id", TOPIC.getAssettopicid());
            values.put("content_id", CONTENT.getContentid());
            GlobalData.sdb.insert("topic_content", null, values);
        }
        cursor = GlobalData.sdb.rawQuery("select * from topic where" + " category_id='"
                + TRAINING_ID.getCateid()
                + "' and topic_id='" + TOPIC.getAssettopicid() + "'", null);
        if (cursor.getCount() == 0) {
            Gson gson1 = new Gson();
            JsonElement jsonElement1 = gson1.toJsonTree(
                    TOPIC, new TypeToken<MyTopic>() {
                    }.getType());
            ContentValues values = new ContentValues();
            values.put("topic", jsonElement1.toString());
            values.put("category_id", TRAINING_ID.getCateid());
            values.put("topic_id", TOPIC.getAssettopicid());
            GlobalData.sdb.insert("topic", null, values);
            GlobalData.showToast(getBaseContext(), "Video saved on local, will sync to server when online", Toast.LENGTH_LONG).show();
        }

//        } else {
//            GlobalData.showToast(getBaseContext(), "Please check your internet connection", Toast.LENGTH_SHORT).show();
//        }
    }

    public void loadContentFile(final ContentFile contentFile) {
        try {
            SELECTED_CONTENT = contentFile;

            if (isFileAlreadyDownload(contentFile)) {
                txtDownload.setAlpha(0.3f);
                imgDownload.setAlpha(0.3f);
                txtDownload.setEnabled(false);
                imgDownload.setEnabled(false);
                txtClear.setAlpha(1.0f);
                imgClear.setAlpha(1.0f);
                txtClear.setEnabled(true);
                imgClear.setEnabled(true);

            } else {
                txtDownload.setAlpha(1f);
                imgDownload.setAlpha(1f);
                txtDownload.setEnabled(true);
                imgDownload.setEnabled(true);
                txtClear.setAlpha(0.3f);
                imgClear.setAlpha(0.3f);
                imgClear.setEnabled(false);
                txtClear.setEnabled(false);
            }
            mTextLanguageSelection.setText(SELECTED_CONTENT.getLanguage_title());
            contentTitle.setText(CONTENT.getTitle());
            title.setText(CONTENT.getTitle());

            contentDescription.setText(CONTENT.getDescription());
            contentDescription.setMovementMethod(new ScrollingMovementMethod());
            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);
                    final String fileName = Objects.requireNonNull(getApplicationContext()).getExternalFilesDir(null)
                            + "/" + ".HYPERM/VIDEO/" + CONTENT.getContentid() + "_" + CONTENT.getVersion() + "_"
                            + contentFile.getLanguage_code() + ".mp4";
                    if (new File(fileName).exists()) {
                        saveTopicData();
                        try {
                            decrypt(fileName, "mp4", 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(contentFile.getFile_url().trim());
                    }

                    videoView.requestFocus();
                    videoView.start();
                    mMediaController.setTitle(CONTENT.getTitle());
                    videoView.setMediaController(mMediaController);
                    videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                        @Override
                        public void onCompletion(MediaPlayer mp) {
                            if (!CONTENT.getStatus().trim().equalsIgnoreCase("2")) {
                                updateStatus("2");
                            }
                        }
                    });

                    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);
                                mBottomLayout.setVisibility(View.GONE);
                            } else {
                                ViewGroup.LayoutParams layoutParams = mVideoLayout.getLayoutParams();
                                layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
                                layoutParams.height = cachedHeight;
                                mVideoLayout.setLayoutParams(layoutParams);
                                mBottomLayout.setVisibility(View.VISIBLE);
                            }
                            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);
                            if (!CONTENT.getStatus().trim().equalsIgnoreCase("1")
                                    && !CONTENT.getStatus().trim().equalsIgnoreCase("2")) {
                                updateStatus("1");
                            }
                        }

                        @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);
        }
    }

    public ContentFile getContentFile() {
        if (CONTENT.getContent_files() == null) {
            return null;
        }
        String language = this.getSharedPreferences("LANGUAGE", Context.MODE_PRIVATE).getString("DEFAULT", "en_us");
        for (ContentFile file : CONTENT.getContent_files()) {
            if (file.getLanguage_code().trim().equalsIgnoreCase(language.trim())) {
                return file;
            }
        }
        return CONTENT.getContent_files().get(0);
    }

    private ArrayList<String> getContentFile(MyContent item) {
        if (item.getContent_files() == null) {
            return null;
        }
        ArrayList<String> Language = new ArrayList<>();
        for (ContentFile file : item.getContent_files()) {
            Language.add(file.getLanguage_title());
        }
        return Language;
    }

    private void showLanguageSelectionList() {
        final ArrayList<String> contentFile = getContentFile(CONTENT);
        builder = new AlertDialog.Builder(VideoViewActivity.this);
        builder.setTitle("SELECT LANGUAGE")
                .setItems(contentFile.toArray(new String[contentFile.size()]), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        loadContentFile(CONTENT.getContent_files().get(i));
                        dialogInterface.dismiss();
                    }
                });

        builder.create().show();

    }

    private void updateStatus(String status) {
        CONTENT.setStatus(status);
        if (new UtilService().isNetworkAvailable(VideoViewActivity.this)) {
            try {
                HashMap<String, String> map = new HashMap<>();
                map.put("contentid", CONTENT.getContentid());
                map.put("assettopicid", CONTENT.getAssettopicid());
                map.put("status", status);

                restService.updateContentStaus(map).enqueue(new MyCallback<ErrorResponse>(status) {
                    @Override
                    public void onResponse(Call<ErrorResponse> call, Response<ErrorResponse> response) {
                        if (response.body() != null && response.body().getStatus() == 200) {
                            CONTENT.setStatus(ids);
                        } else if (response.body() != null && response.body().getStatus() == 401) {
                            GlobalData.canLogout = true;
                            finish();
                        } else if (response.errorBody() != null) {
                            Gson gson = new Gson();
                            ErrorResponse message = gson.fromJson(response.errorBody().charStream(), ErrorResponse.class);
                            GlobalData.showToast(VideoViewActivity.this, message.getMessage(), Toast.LENGTH_SHORT).show();
                            if (message.getStatus() == 401) {
                                GlobalData.canLogout = true;
                                finish();
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<ErrorResponse> call, Throwable t) {

                    }
                });

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

    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();
            getToTime();
            this.overridePendingTransition(R.anim.animation_f_enter,
                    R.anim.animation_f_leave);
        }


    }

    private void getToTime() {
        c = Calendar.getInstance();
        System.out.println("toTime " + c.getTime());
        df = new SimpleDateFormat("HH:mm:ss");
        toTime = df.format(c.getTime());
        finalTime = UtilService.getTimeInterval(this,df,fromTime,toTime);
        if (StorePreference.getInstance(this).getBooleanValue(GlobalData.ISDSELOGIN))
            sendHitCountToServer();
    }

    @Override
    protected void onSaveInstanceState(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();
        }
    }
}