package com.hainaos.vc.activity.video;

import android.content.res.Configuration;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Environment;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.SimpleItemAnimator;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.arialyy.annotations.Download;
import com.arialyy.aria.core.Aria;
import com.arialyy.aria.core.task.DownloadTask;
import com.google.gson.JsonObject;
import com.hainaos.vc.R;
import com.hainaos.vc.adapter.VideoAdapter;
import com.hainaos.vc.base.mvvm.BaseMvvmActivity;
import com.hainaos.vc.bean.LocalVideoInfo;
import com.hainaos.vc.databinding.ActivityVideoBinding;
import com.hainaos.vc.gson.GsonUtils;
import com.hainaos.vc.utils.SPUtils;
import com.hainaos.vc.utils.ToastUtil;
import com.hainaos.vc.utils.VideoUtils;
import com.hainaos.vc.view.CustomDialog;
import com.hainaos.vc.view.RecycleGridLayoutManager;

import java.io.File;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class VideoActivity extends BaseMvvmActivity<VideoViewModel, ActivityVideoBinding> {
    private static final String TAG = "VideoActivity";

    private List<String> mPaths = new ArrayList<>();
    private RecycleGridLayoutManager mManager;
    private VideoAdapter mVideoAdapter;

    @Override
    public boolean setNightMode() {
        return false;
    }


    @Override
    public int getLayoutId() {
        return R.layout.activity_video;
    }

    @Override
    protected void initDataBinding() {
        mViewModel.setCtx(this);
        mViewModel.setVDBinding(mViewDataBinding);
        mViewModel.setLifecycle(getLifecycleSubject());
        mViewDataBinding.setClick(new BtnClick());
    }

    @Override
    public void initView() {
        Aria.download(this).register();

//        initActionBar();
        mViewDataBinding.swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mViewModel.getHomeVideo();
            }
        });
        ((SimpleItemAnimator) mViewDataBinding.recyclerView.getItemAnimator()).setSupportsChangeAnimations(false);
        int orientation = getResources().getConfiguration().orientation;
        if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
            mManager = new RecycleGridLayoutManager(VideoActivity.this, 3);
        } else if (orientation == Configuration.ORIENTATION_PORTRAIT) {
            mManager = new RecycleGridLayoutManager(VideoActivity.this, 2);
        }
        mViewDataBinding.recyclerView.setLayoutManager(mManager);
        mViewDataBinding.recyclerView.setNestedScrollingEnabled(false);

        ((DefaultItemAnimator) mViewDataBinding.recyclerView.getItemAnimator()).setSupportsChangeAnimations(false);
        mVideoAdapter = new VideoAdapter(VideoActivity.this);
        mVideoAdapter.setOnLongClickListener(new VideoAdapter.onItemLongClickListener() {
            @Override
            public void onItemLongClick(String path, int position) {
                showDialog(path, position);
            }
        });
        mViewDataBinding.recyclerView.setAdapter(mVideoAdapter);
    }

    @Override
    public void initData() {
        mViewModel.mPhotoInfosData.observe(this, new Observer<ArrayList<LocalVideoInfo>>() {
            @Override
            public void onChanged(ArrayList<LocalVideoInfo> localVideoInfos) {
                if (localVideoInfos == null || localVideoInfos.size() == 0) {
                    mViewDataBinding.clNodata.setVisibility(View.VISIBLE);
                    mViewDataBinding.recyclerView.setVisibility(View.GONE);
                    ToastUtil.show("没有数据");
                } else {
                    mViewDataBinding.clNodata.setVisibility(View.GONE);
                    mViewDataBinding.recyclerView.setVisibility(View.VISIBLE);
                    mVideoAdapter.setData(localVideoInfos);
                }
                mViewDataBinding.tvScan.setVisibility(View.GONE);
                mViewDataBinding.swipeRefreshLayout.setRefreshing(false);
            }
        });
        mViewModel.mCompleteData.observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean aBoolean) {
                mViewDataBinding.swipeRefreshLayout.setRefreshing(false);
            }
        });
        getHomeVideo();
    }

    private void getHomeVideo() {
        mViewDataBinding.swipeRefreshLayout.setRefreshing(true);
        mViewModel.getHomeVideo();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        Configuration config = getResources().getConfiguration();
        if (config.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            mManager = new RecycleGridLayoutManager(VideoActivity.this, 2);
            mViewDataBinding.recyclerView.setLayoutManager(mManager);
        }
        if (config.orientation == Configuration.ORIENTATION_PORTRAIT) {
            mManager = new RecycleGridLayoutManager(VideoActivity.this, 3);
            mViewDataBinding.recyclerView.setLayoutManager(mManager);
        }
    }

    private void showDialog(String path, int position) {
        CustomDialog dialog = new CustomDialog(VideoActivity.this);
        dialog.setTitle("删除文件")
                .setMessage("确定要删除文件 " + VideoUtils.getFileNameWithoutExtension(path) + "吗")
                .setPositive("确定")
                .setNegtive("取消")
                .setOnClickBottomListener(new CustomDialog.OnClickBottomListener() {
                    @Override
                    public void onPositiveClick() {
                        dialog.dismiss();
                        File file = new File(path);
                        if (file.delete()) {
                            mVideoAdapter.removeItem(position);
                            ToastUtil.show("删除成功");
                        } else {
                            ToastUtil.show("删除失败，检查权限是否开启");
                        }
                    }

                    @Override
                    public void onNegtiveClick() {
                        dialog.dismiss();
                    }
                });
        dialog.show();
    }


    private void initActionBar() {
        setToolbarCustomTheme();
        //显示返回按钮
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setHomeButtonEnabled(true);
            actionBar.setDisplayHomeAsUpEnabled(true);
            SpannableString spannableString = new SpannableString(getString(R.string.app_name));
            ForegroundColorSpan colorSpan = new ForegroundColorSpan(getResources().getColor(R.color.defaultColor));
            spannableString.setSpan(colorSpan, 0, spannableString.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
            actionBar.setTitle(spannableString);
        }
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
    }

    //自定义颜色返回按钮
    protected void setToolbarCustomTheme() {
        Drawable upArrow = ContextCompat.getDrawable(this, R.drawable.abc_ic_ab_back_material);
        if (upArrow != null) {
            upArrow.setColorFilter(ContextCompat.getColor(this, R.color.defaultColor), PorterDuff.Mode.SRC_ATOP);
            if (getSupportActionBar() != null) {
                getSupportActionBar().setHomeAsUpIndicator(upArrow);
            }
        }
    }

    public void traverseFolder(String path) {
        int fileNum = 0, folderNum = 0;
        File file = new File(path);
        if (file.exists()) {
            LinkedList<File> list = new LinkedList<File>();
            File[] files = file.listFiles();
            for (File file2 : files) {
                if (file2.isDirectory()) {
                    Log.e("traverseFolder1", "文件夹:" + file2.getAbsolutePath());
                    list.add(file2);
                    folderNum++;
                } else {
                    Log.e("traverseFolder1", "文件:" + file2.getAbsolutePath());
                    fileNum++;
                }
            }
            File temp_file;
            while (!list.isEmpty()) {
                temp_file = list.removeFirst();
                files = temp_file.listFiles();
                for (File file2 : files) {
                    if (file2.isDirectory()) {
                        Log.e("traverseFolder2", "文件夹:" + file2.getAbsolutePath());
                        list.add(file2);
                        folderNum++;
                    } else {
                        Log.e("traverseFolder2", "文件:" + file2.getAbsolutePath());
                        fileNum++;
                    }
                }
            }
        } else {
            Log.e("traverseFolder1", "文件不存在!");
        }
        Log.e("traverseFolder1", "文件夹共有:" + folderNum + ",文件共有:" + fileNum);
    }


    public class ScanTask extends AsyncTask<Void, String, List<String>> {

        @Override
        protected List<String> doInBackground(Void... voids) {
            long s1 = System.currentTimeMillis();
            mPaths.clear();
            List<String> fileList = new ArrayList<>();
            String rootPath = Environment.getExternalStorageDirectory().getPath() + File.separator;
            File file = new File(rootPath);
            if (file.exists()) {
                LinkedList<File> list = new LinkedList<File>();
                File[] files = file.listFiles();
                if (files == null) return null;
                for (File file2 : files) {
                    publishProgress(file2.getAbsolutePath());
                    if (file2.isDirectory()) {
                        list.add(file2);
                    } else {
                        if (VideoUtils.isVideoFormat(file2.getAbsolutePath())) {
                            fileList.add(file2.getAbsolutePath());
                        }
                    }
                }
                File temp_file;
                while (!list.isEmpty()) {
                    temp_file = list.removeFirst();
                    files = temp_file.listFiles();
                    if (files == null) {
                        continue;
                    }
                    for (File file2 : files) {
                        publishProgress(file2.getAbsolutePath());
                        if (file2.isDirectory()) {
                            list.add(file2);
                        } else {
                            if (VideoUtils.isVideoFormat(file2.getAbsolutePath())) {
                                fileList.add(file2.getAbsolutePath());
                            }
                        }
                    }
                }
            } else {
                Log.e("traverseFolder1", "文件不存在!");
            }
            Log.e("ScanTask", "doInBackground: " + "Scan time = " + (System.currentTimeMillis() - s1) + "ms");
            return fileList;
        }

        @Override
        protected void onProgressUpdate(String... values) {
            super.onProgressUpdate(values);
            mPaths.add(values[0]);
            mViewDataBinding.tvScan.setVisibility(View.VISIBLE);
            mViewDataBinding.tvScan.setText("正在扫描：" + values[0]);
//            adapter.setData(paths);
        }

        @Override
        protected void onPostExecute(List<String> strings) {
            super.onPostExecute(strings);
            Log.e("ScanTask", "onPostExecute: " + strings.size());
            if (strings.size() == 0) {
                mViewDataBinding.clNodata.setVisibility(View.VISIBLE);
                mViewDataBinding.recyclerView.setVisibility(View.GONE);
            } else {
                mViewDataBinding.clNodata.setVisibility(View.GONE);
                mViewDataBinding.recyclerView.setVisibility(View.VISIBLE);
//                adapter.setData(strings);
            }
            mViewDataBinding.tvScan.setVisibility(View.GONE);
            mViewDataBinding.swipeRefreshLayout.setRefreshing(false);
        }
    }

    private MenuItem refresh, single_loop, loop;

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        refresh = menu.findItem(R.id.refresh);
        single_loop = menu.findItem(R.id.single_loop);
        loop = menu.findItem(R.id.loop);
        updateMenuIcon();
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        //返回按钮点击事件
        switch (item.getItemId()) {
            case R.id.setting:

                break;
            case android.R.id.home:
                if (System.currentTimeMillis() - mPreClickTime > 1000) {
                    ToastUtil.show("再按一次，退出");
                    mPreClickTime = System.currentTimeMillis();
                } else {
                    finish();
                }
                break;
            case R.id.refresh:
                getHomeVideo();
                break;
            case R.id.single_loop:
                if (null != single_loop) {
                    int singleLoop = (int) SPUtils.get(VideoActivity.this, "single_loop", 0);
                    if (singleLoop == 0) {
                        SPUtils.put(VideoActivity.this, "single_loop", 1);
                        SPUtils.put(VideoActivity.this, "loop", 0);
                        single_loop.setIcon(R.drawable.menu_selected);
                    } else {
                        SPUtils.put(VideoActivity.this, "single_loop", 0);
                        single_loop.setIcon(R.drawable.menu_transparent);
                    }
                }
                break;
            case R.id.loop:
                if (null != loop) {
                    int singleLoop = (int) SPUtils.get(VideoActivity.this, "loop", 0);
                    if (singleLoop == 0) {
                        SPUtils.put(VideoActivity.this, "single_loop", 0);
                        SPUtils.put(VideoActivity.this, "loop", 1);
                        loop.setIcon(R.drawable.menu_selected);
                    } else {
                        SPUtils.put(VideoActivity.this, "loop", 0);
                        loop.setIcon(R.drawable.menu_transparent);
                    }
                }
                break;
            default:
                break;
        }
        updateMenuIcon();
        return super.onOptionsItemSelected(item);
    }

    private long mPreClickTime;

    private void updateMenuIcon() {
        if (null != refresh) {

        }
        if (null != single_loop) {
            int singleLoop = (int) SPUtils.get(VideoActivity.this, "single_loop", 0);
            if (singleLoop == 0) {
                single_loop.setIcon(R.drawable.menu_transparent);
            } else {
                single_loop.setIcon(R.drawable.menu_selected);
            }
        }
        if (null != loop) {
            int singleLoop = (int) SPUtils.get(VideoActivity.this, "loop", 0);
            if (singleLoop == 0) {
                loop.setIcon(R.drawable.menu_transparent);
            } else {
                loop.setIcon(R.drawable.menu_selected);
            }
        }
    }

    public class BtnClick {
        public void exie(View view) {
            finish();
        }

        public void refresh(View view) {
            getHomeVideo();
        }
    }

    //在这里处理任务执行中的状态，如进度进度条的刷新
    @Download.onTaskRunning
    void running(DownloadTask task) {
        Log.e("aria running", "正在下载:" + task.getState() + "-" + task.getPercent() + "--" + task.getExtendField());
        try {
            String jsonString = task.getExtendField();
            JsonObject jsonObject = GsonUtils.getJsonObject(jsonString);
        } catch (Exception e) {
            Log.e("running", "running: " + e.getMessage());
        }
    }

    @Download.onTaskComplete
    void taskComplete(DownloadTask task) {
        //在这里处理任务完成的状态
        Log.e("taskComplete", task.getExtendField());
//        Aria.download(this).load(task.getDownloadEntity().getId()).cancel();
        mViewModel.getHomeVideo();
    }

    @Download.onTaskFail
    void taskFail(DownloadTask task, Exception e) {
        Aria.download(this).resumeAllTask();
        final String filepath = task.getFilePath();
        final String packageName = task.getExtendField();
        try {
            Aria.download(this).load(task.getDownloadEntity().getId()).cancel(true);
            Log.e(TAG, "taskFail: " + "Exception: " + e.getLocalizedMessage());
        } catch (Exception ex) {

        }
        Log.e(TAG, "taskFail: " + packageName + "filepath： " + filepath);
        mViewModel.getHomeVideo();
    }
}
