package com.qboxus.tictic.activitesfragments.soundlists;

import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.RequiresApi;

import com.qboxus.tictic.activitesfragments.videorecording.VideoRecoderActivity;
import com.qboxus.tictic.databinding.ActivityVideoSoundBinding;
import com.qboxus.tictic.simpleclasses.AppCompatLocaleActivity;

import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.ParcelFileDescriptor;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.AbsListView;

import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.MediaItem;
import com.google.android.exoplayer2.audio.AudioAttributes;
import com.google.android.exoplayer2.source.MediaSource;
import com.google.android.exoplayer2.source.ProgressiveMediaSource;
import com.google.android.exoplayer2.upstream.DataSource;
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory;
import com.qboxus.tictic.activitesfragments.WatchVideosActivity;
import com.qboxus.tictic.Constants;
import com.qboxus.tictic.models.HomeModel;
import com.qboxus.tictic.adapters.MyVideosAdapter;
import com.qboxus.tictic.R;
import com.qboxus.tictic.interfaces.AdapterClickListener;
import com.qboxus.tictic.apiclasses.ApiLinks;
import com.volley.plus.VPackages.VolleyRequest;
import com.volley.plus.interfaces.Callback;

import com.qboxus.tictic.simpleclasses.DataHolder;
import com.qboxus.tictic.simpleclasses.DataParsing;
import com.qboxus.tictic.simpleclasses.Dialogs;
import com.qboxus.tictic.simpleclasses.FileUtils;
import com.qboxus.tictic.simpleclasses.Functions;
import com.qboxus.tictic.simpleclasses.PermissionUtils;
import com.qboxus.tictic.simpleclasses.Variables;
import com.downloader.Error;
import com.downloader.OnDownloadListener;
import com.downloader.PRDownloader;
import com.downloader.request.DownloadRequest;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.trackselection.DefaultTrackSelector;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class VideoSoundActivity extends AppCompatLocaleActivity implements View.OnClickListener {

    HomeModel item;
    File audioFile;
    GridLayoutManager linearLayoutManager;
    int pageCount = 0;
    boolean ispostFinsh;
    ArrayList<HomeModel> dataList;
    MyVideosAdapter adapter;


    ActivityVideoSoundBinding binding;
    PermissionUtils takePermissionUtils;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Functions.setLocale(Functions.getSharedPreference(VideoSoundActivity.this).getString(Variables.APP_LANGUAGE_CODE,Variables.DEFAULT_LANGUAGE_CODE)
                , this, getClass(),false);
        binding = ActivityVideoSoundBinding.inflate(getLayoutInflater());

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {

            getWindow().setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
                    WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
        }

        setContentView(binding.getRoot());

        FileUtils.makeDirectry(FileUtils.getAppFolder(this)+Variables.APP_HIDED_FOLDER);
        FileUtils.makeDirectry(FileUtils.getAppFolder(this)+Variables.DRAFT_APP_FOLDER);


        Intent intent = getIntent();
        if (intent.hasExtra("data")) {
            item = (HomeModel) intent.getParcelableExtra("data");
        }

        takePermissionUtils=new PermissionUtils(VideoSoundActivity.this,mPermissionResult);

        binding.backBtn.setOnClickListener(this);
        binding.useAudioBtn.setOnClickListener(this);
        binding.playBtn.setOnClickListener(this);
        binding.pauseBtn.setOnClickListener(this);
        binding.favbtn.setOnClickListener(this);


        Functions.printLog(Constants.tag, item.getSound_pic());
        Functions.printLog(Constants.tag, item.getSound_url_acc());

        saveAudio();


        linearLayoutManager = new GridLayoutManager(VideoSoundActivity.this, 3);
        binding.recylerview.setLayoutManager(linearLayoutManager);

        dataList = new ArrayList<>();

        adapter = new MyVideosAdapter(this, dataList,"sound", new AdapterClickListener() {
            @Override
            public void onItemClick(View view, int pos, Object object) {

                HomeModel item = (HomeModel) object;
                openWatchVideo(pos);


            }
        });
        binding.recylerview.setAdapter(adapter);

        binding.recylerview.addOnScrollListener(new RecyclerView.OnScrollListener() {
            boolean userScrolled;
            int scrollOutitems;

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) {
                    userScrolled = true;
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

                scrollOutitems = linearLayoutManager.findLastVisibleItemPosition();

                Functions.printLog("resp", "" + scrollOutitems);
                if (userScrolled && (scrollOutitems == dataList.size() - 1)) {
                    userScrolled = false;

                    if (binding.loadMoreProgress.getVisibility() != View.VISIBLE && !ispostFinsh) {
                        binding.loadMoreProgress.setVisibility(View.VISIBLE);
                        pageCount = pageCount + 1;
                        callApi();
                    }
                }


            }
        });


        setData();


        pageCount = 0;
        callApi();


    }



    void setData(){

//        if ((item.name == null || item.name.equals("") || item.name.equals("null"))) {
//            binding.soundName.setText(getString(R.string.orignal_sound_)+" " + item.first_name + " " + item.last_name);
//        } else {
//            binding.soundName.setText(item.name);
//        }

        binding.usernametxt.setText(getString(R.string.created_by)+ item.getUserModel().username);
        binding.soundImage.setController(Functions.frescoImageLoad(item.getSound_pic(),R.drawable.ractengle_solid_primary,binding.soundImage,false));


        if (item.soundFav != null && item.soundFav.equalsIgnoreCase("1")) {

            binding.favImg.setImageDrawable(ContextCompat.getDrawable(this,R.drawable.ic_fav_fill));
            binding.favtxt.setText(getString(R.string.added_to_favourite));
        } else {

            binding.favImg.setImageDrawable(ContextCompat.getDrawable(this,R.drawable.ic_fav));
            binding.favtxt.setText(getString(R.string.add_to_favourite));
        }

    }


    private void callApiForFavSound() {

        JSONObject parameters = new JSONObject();
        try {
           parameters.put("sound_id", item.sound_id);


        } catch (Exception e) {
            e.printStackTrace();
        }

        Functions.showLoader(this, false, false);
        VolleyRequest.JsonPostRequest(this, ApiLinks.addSoundFavourite, parameters, Functions.getHeaders(this),new Callback() {
            @Override
            public void onResponce(String resp) {
                Functions.checkStatus(VideoSoundActivity.this,resp);
                Functions.cancelLoader();

                if (item.soundFav.equals("1"))
                    item.soundFav = "0";
                else
                    item.soundFav = "1";

                setData();
            }
        });

    }




    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.back_btn:
                onBackPressed();
                break;

            case R.id.favbtn:
                if (Functions.checkLoginUser(VideoSoundActivity.this))
                {
                    callApiForFavSound();
                }
                break;

            case R.id.useAudioBtn:
                if (Functions.checkLoginUser(VideoSoundActivity.this)) {
                    if (audioFile != null && audioFile.exists()) {
                        stopPlaying();
                        openVideoRecording();
                    }
                }
                break;

            case R.id.play_btn:
                if (audioFile != null && audioFile.exists())
                    playaudio();

                break;

            case R.id.pause_btn:
                stopPlaying();
                break;
        }
    }

    private void saveAudiointoExternalStorage() {
        if (audioFile != null && audioFile.exists()) {
            try {

                String soundPath="";
                if (Build.VERSION.SDK_INT>Build.VERSION_CODES.P)
                {
                    soundPath=FileUtils.getAppFolder(VideoSoundActivity.this);
                }
                else
                {
                    soundPath=Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC).getAbsolutePath();
                }

                progressDialog = new ProgressDialog(this);
                progressDialog.setMessage(getString(R.string.please_wait_));
                progressDialog.setCancelable(false);
                progressDialog.setCanceledOnTouchOutside(false);
                progressDialog.show();
                String fileName=Functions.getRandomString(5)+Variables.SelectedAudio_AAC;

                prDownloader = PRDownloader.download(item.getSound_url_acc(), soundPath, fileName)
                        .build();

                String finalSoundPath = soundPath;
                prDownloader.start(new OnDownloadListener() {
                    @Override
                    public void onDownloadComplete() {
                        progressDialog.dismiss();
                        if (Build.VERSION.SDK_INT>Build.VERSION_CODES.P)
                        {
                            downloadAEAudio(finalSoundPath,fileName);
                        }
                        else
                        {
                            scanFile(finalSoundPath);
                        }

                    }

                    @Override
                    public void onError(Error error) {
                        progressDialog.dismiss();
                    }
                });


            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    public void downloadAEAudio(String path, String audioName) {

        ContentValues valuesaudio;
        valuesaudio = new ContentValues();
        valuesaudio.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_MUSIC);
        valuesaudio.put(MediaStore.MediaColumns.TITLE, audioName);
        valuesaudio.put(MediaStore.Audio.Media.ARTIST, "");
        valuesaudio.put(MediaStore.Audio.Media.ALBUM, "");
        valuesaudio.put(MediaStore.MediaColumns.DISPLAY_NAME, audioName);
        valuesaudio.put(MediaStore.MediaColumns.MIME_TYPE, "audio/aac");
        valuesaudio.put(MediaStore.MediaColumns.DATE_ADDED, System.currentTimeMillis() / 1000);
        valuesaudio.put(MediaStore.MediaColumns.DATE_TAKEN, System.currentTimeMillis());
        valuesaudio.put(MediaStore.MediaColumns.IS_PENDING, 1);
        ContentResolver resolver = getContentResolver();
        Uri uriSavedAudio = resolver.insert(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, valuesaudio);

        ParcelFileDescriptor pfd;

        try {
            pfd = getContentResolver().openFileDescriptor(uriSavedAudio, "w");

            FileOutputStream out = new FileOutputStream(pfd.getFileDescriptor());

            File audioFile = new File(path+audioName);

            FileInputStream in = new FileInputStream(audioFile);


            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {

                out.write(buf, 0, len);
            }


            out.close();
            in.close();
            pfd.close();


            Dialogs.showAlert(VideoSoundActivity.this, VideoSoundActivity.this.getString(R.string.audio_saved), VideoSoundActivity.this.getString(R.string.this_sound_is_successfully_saved));

        } catch (Exception e) {

            e.printStackTrace();
        }


        valuesaudio.clear();
        valuesaudio.put(MediaStore.MediaColumns.IS_PENDING, 0);
        getContentResolver().update(uriSavedAudio, valuesaudio, null, null);
    }

    public void scanFile(String downloadDirectory) {

        MediaScannerConnection.scanFile(VideoSoundActivity.this,
                new String[]{downloadDirectory+Variables.SelectedAudio_AAC},
                null,
                new MediaScannerConnection.OnScanCompletedListener() {

                    public void onScanCompleted(String path, Uri uri) {
                        Dialogs.showAlert(VideoSoundActivity.this, VideoSoundActivity.this.getString(R.string.audio_saved), VideoSoundActivity.this.getString(R.string.this_sound_is_successfully_saved));

                    }
                });
    }


    // get the video list sound id
    public void callApi() {
        JSONObject params = new JSONObject();
        try {

            params.put("sound_id", item.sound_id);
            params.put("starting_point", "" + pageCount);


        } catch (Exception e) {
            e.printStackTrace();
        }
        VolleyRequest.JsonPostRequest(this, ApiLinks.showVideosAgainstSound, params,Functions.getHeaders(this), new Callback() {
            @Override
            public void onResponce(String resp) {
                Functions.checkStatus(VideoSoundActivity.this,resp);
                parseVideo(resp);


            }
        });

    }


    // parse the data of the video list against sound id
    public void parseVideo(String responce) {
        try {
            JSONObject jsonObject = new JSONObject(responce);
            String code = jsonObject.optString("code");
            if (code.equals("200")) {
                JSONArray msgArray = jsonObject.getJSONArray("msg");

                ArrayList<HomeModel> temp_list = new ArrayList<>();

                for (int i = 0; i < msgArray.length(); i++) {
                    JSONObject itemdata = msgArray.optJSONObject(i);

                    JSONObject video = itemdata.optJSONObject("Video");
                    JSONObject user = itemdata.optJSONObject("User");
                    JSONObject sound = itemdata.optJSONObject("Sound");
                    JSONObject location = itemdata.optJSONObject("Location");
                    JSONObject store = itemdata.optJSONObject("Store");
                    JSONObject videoProduct=itemdata.optJSONObject("Product");
                    JSONObject userPrivacy = user.optJSONObject("PrivacySetting");
                    JSONObject userPushNotification = user.optJSONObject("PushNotification");

                    HomeModel item = DataParsing.parseVideoData(user, sound, video,location,store,videoProduct, userPrivacy, userPushNotification);
                    if (Functions.isStringHasValue(item.getUserModel().username))
                    {
                        temp_list.add(item);
                    }

                }

                if (temp_list.isEmpty())
                    ispostFinsh = true;
                else {
                    dataList.addAll(temp_list);
                    adapter.notifyDataSetChanged();
                }


            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            binding.loadMoreProgress.setVisibility(View.GONE);
        }

    }


    // open the video in full screen
    private void openWatchVideo(int postion) {
        Intent intent = new Intent(VideoSoundActivity.this, WatchVideosActivity.class);
        Bundle args = new Bundle();
        args.putSerializable("arraylist", dataList);
        DataHolder.Companion.getInstance().setData(args);

        intent.putExtra("position", postion);
        intent.putExtra("pageCount", pageCount);
        intent.putExtra("soundId", item.sound_id);
        intent.putExtra("userId",Functions.getSharedPreference(VideoSoundActivity.this).getString(Variables.U_ID,""));
        intent.putExtra("whereFrom","videoSound");
        startActivity(intent);
    }




    SimpleExoPlayer player;
    public void playaudio() {

        DefaultTrackSelector trackSelector = new DefaultTrackSelector(this);

        player = new SimpleExoPlayer.Builder(this).
                setTrackSelector(trackSelector)
                .build();

        DataSource.Factory cacheDataSourceFactory = new DefaultDataSourceFactory(VideoSoundActivity.this, getString(R.string.app_name));
        MediaSource videoSource = new ProgressiveMediaSource.Factory(cacheDataSourceFactory).createMediaSource(MediaItem.fromUri(item.getSound_url_mp3()));
        player.setMediaSource(videoSource);
        player.prepare();
        player.setPlayWhenReady(true);

        try {
            AudioAttributes audioAttributes = new AudioAttributes.Builder()
                    .setUsage(C.USAGE_MEDIA)
                    .setContentType(C.AUDIO_CONTENT_TYPE_MOVIE)
                    .build();
            player.setAudioAttributes(audioAttributes, true);
        }
        catch (Exception e)
        {
            Log.d(Constants.tag,"Exception audio focus : "+e);
        }

        showPlayingState();
    }


    public void stopPlaying() {
        if (player != null) {
            player.setPlayWhenReady(false);
        }
        showPauseState();
    }


    @Override
    public void onBackPressed() {
        stopPlaying();
        finish();
    }

    @Override
    protected void onStop() {
        super.onStop();
        stopPlaying();
        Functions.printLog(Constants.tag, "onStop");

    }


    // show the player state
    public void showPlayingState() {
        binding.playBtn.setVisibility(View.GONE);
        binding.pauseBtn.setVisibility(View.VISIBLE);
    }

    public void showPauseState() {
        binding.playBtn.setVisibility(View.VISIBLE);
        binding.pauseBtn.setVisibility(View.GONE);
    }

    DownloadRequest prDownloader;
    ProgressDialog progressDialog;

    public void saveAudio() {
        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage(getString(R.string.please_wait_));
        progressDialog.setCancelable(false);
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.show();

        prDownloader = PRDownloader.download(item.getSound_url_mp3(), FileUtils.getAppFolder(this), Variables.SelectedAudio_AAC)
                .build();

        prDownloader.start(new OnDownloadListener() {
            @Override
            public void onDownloadComplete() {

                progressDialog.dismiss();
                audioFile = new File(FileUtils.getAppFolder(VideoSoundActivity.this) + Variables.SelectedAudio_AAC);
                showPauseState();

            }

            @Override
            public void onError(Error error) {
                progressDialog.dismiss();
            }
        });


    }


    // open the camera for recording video
    public void openVideoRecording() {
        Intent intent = new Intent(VideoSoundActivity.this, VideoRecoderActivity.class);
        intent.putExtra("name", binding.soundName.getText().toString());
        intent.putExtra("sound_id", item.sound_id);
        intent.putExtra("isSelected", "yes");
        startActivity(intent);
        overridePendingTransition(R.anim.in_from_bottom, R.anim.out_to_top);

    }

    private ActivityResultLauncher<String[]> mPermissionResult = registerForActivityResult(
            new ActivityResultContracts.RequestMultiplePermissions(), new ActivityResultCallback<Map<String, Boolean>>() {
                @RequiresApi(api = Build.VERSION_CODES.M)
                @Override
                public void onActivityResult(Map<String, Boolean> result) {

                    boolean allPermissionClear=true;
                    List<String> blockPermissionCheck=new ArrayList<>();
                    for (String key : result.keySet())
                    {
                        if (!(result.get(key)))
                        {
                            allPermissionClear=false;
                            blockPermissionCheck.add(Functions.getPermissionStatus(VideoSoundActivity.this,key));
                        }
                    }
                    if (blockPermissionCheck.contains("blocked"))
                    {
                        Functions.showPermissionSetting(VideoSoundActivity.this,getString(R.string.we_need_storage_permission_for_save_sound));
                    }
                    else
                    if (allPermissionClear)
                    {
                        saveAudiointoExternalStorage();
                    }

                }
            });


    @Override
    protected void onDestroy() {
        mPermissionResult.unregister();
        super.onDestroy();
    }



}
