package com.hainaos.vc.fragment.video;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.DefaultItemAnimator;
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.fragment.BaseMvvmFragment;
import com.hainaos.vc.bean.LocalVideoInfo;
import com.hainaos.vc.databinding.FragmentVideoBinding;
import com.hainaos.vc.gson.GsonUtils;
import com.hainaos.vc.utils.ScreenUtils;
import com.hainaos.vc.utils.ToastUtil;
import com.hainaos.vc.utils.VideoUtils;
import com.hainaos.vc.view.CustomDialog;
import com.hainaos.vc.view.EquallyDividedItemDecoration;
import com.hainaos.vc.view.RecycleGridLayoutManager;

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

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link VideoFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class VideoFragment extends BaseMvvmFragment<VideoViewModel, FragmentVideoBinding> {
    private static final String TAG = "VideoFragment";

    private Activity mContext;

    private RecycleGridLayoutManager mManager;
    private VideoAdapter mVideoAdapter;
    private static final int SPAN_COUNT = 2;

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    public VideoFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment PictureFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static VideoFragment newInstance(String param1, String param2) {
        VideoFragment fragment = new VideoFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_video;
    }

    @Override
    protected void initDataBinding() {
        mContext = getActivity();
        mViewModel.setCtx(getCtx());
        mViewModel.setLifecycle(getLifecycleSubject());
        mViewModel.setVDBinding(mViewDataBinding);
//        mViewDataBinding.setClick(new BtnClick());
    }

    @Override
    protected void initView(Bundle bundle) {
        Aria.download(this).register();

        mViewDataBinding.swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mViewModel.getHomeVideo();
                mViewDataBinding.swipeRefreshLayout.setRefreshing(true);
            }
        });
        mManager = new RecycleGridLayoutManager(mContext, SPAN_COUNT);
        mViewDataBinding.recyclerView.setLayoutManager(mManager);

        EquallyDividedItemDecoration equallyDividedItemDecoration = new EquallyDividedItemDecoration(SPAN_COUNT, ScreenUtils.dip2px(mContext, 1));
        mViewDataBinding.recyclerView.addItemDecoration(equallyDividedItemDecoration);
        mViewDataBinding.recyclerView.setNestedScrollingEnabled(false);

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

        mViewModel.getHomeVideo();
        mViewDataBinding.swipeRefreshLayout.setRefreshing(true);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {

    }

    @Override
    public void fetchData() {
        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.swipeRefreshLayout.setRefreshing(false);
            }
        });
        mViewModel.mCompleteData.observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean aBoolean) {
                mViewDataBinding.swipeRefreshLayout.setRefreshing(false);
            }
        });

    }

    private void showDialog(String path, int position) {
        CustomDialog dialog = new CustomDialog(mContext);
        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();
    }


    //在这里处理任务执行中的状态，如进度进度条的刷新
    @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();
    }
}
