package com.sheep.gamegroup.module.find.activity;


import android.app.Activity;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.view.View;

import com.alibaba.fastjson.JSONObject;
import com.kfzs.cfyl.share_library.util.CallBackAPI;
import com.kfzs.cfyl.share_library.util.Constant;
import com.sheep.gamegroup.absBase.AbsObserver;
import com.sheep.gamegroup.absBase.BaseActivity;
import com.sheep.gamegroup.absBase.IRefresh;
import com.sheep.gamegroup.model.entity.DiscoveryTopic;
import com.sheep.gamegroup.model.entity.Video;
import com.sheep.gamegroup.module.find.fragment.FgtMediaPickerImg;
import com.sheep.gamegroup.module.find.fragment.FgtMediaPickerVideo;
import com.sheep.gamegroup.util.CommonUtil;
import com.sheep.gamegroup.util.DataUtil;
import com.sheep.gamegroup.util.Jump2View;
import com.sheep.gamegroup.util.ListUtil;
import com.sheep.gamegroup.util.TestUtil;
import com.sheep.gamegroup.util.ViewUtil;
import com.sheep.gamegroup.view.adapter.TitleFragmentListAdapter;
import com.sheep.jiuyan.samllsheep.R;
import com.sheep.jiuyan.samllsheep.utils.G;
import com.sheep.jiuyan.samllsheep.utils.TitleBarUtils;

import org.afinal.simplecache.ApiKey;
import org.greenrobot.eventbus.EventBus;

import java.io.Serializable;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import cn.finalteam.rxgalleryfinal.api.CameraCallBack;
import cn.finalteam.rxgalleryfinal.bean.MediaBean;
import cn.finalteam.rxgalleryfinal.utils.CameraUtil;
import cn.finalteam.rxgalleryfinal.utils.MediaUtils;
import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by realicing on 2018/11/26.
 * realicing@sina.com
 * 小绵羊3.4.5新增--发布发现内容--选择视频和图片
 */
public class ActMediaChoose extends BaseActivity {

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

    @BindView(R.id.indicator)
    TabLayout indicator;
    @BindView(R.id.below_tab_line)
    View below_tab_line;
    @BindView(R.id.viewPager)
    ViewPager viewPager;

    private TitleFragmentListAdapter mAdapter;

    @Override
    public void initView() {
        TitleBarUtils.getInstance()
                .setShowOrHide(this, true)
                .setTitle(this, "选择媒体")
                .setTitleFinish(this)
                .setRightImgBotton(this, R.mipmap.ic_open_camera, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
//                Jump2View.getInstance().goActEditVideo(video);
                        boolean isVideo = mAdapter.getItem(viewPager.getCurrentItem()) instanceof FgtMediaPickerVideo;
                        filePath = CameraUtil.openCamera(ActMediaChoose.this, !isVideo);
                    }
                });

        mAdapter = new TitleFragmentListAdapter(getSupportFragmentManager());
        mAdapter.add(new FgtMediaPickerVideo(), "视频");
        if (TestUtil.isDev()) {
            mAdapter.add(new FgtMediaPickerImg(), "图片");
        }
        viewPager.setAdapter(mAdapter);
        indicator.setupWithViewPager(viewPager);
        viewPager.setCurrentItem(0);
        viewPager.setOffscreenPageLimit(mAdapter.getCount());
        CommonUtil.getInstance().reflex(indicator, this);
        if (mAdapter.getCount() < 2) {
            ViewUtil.setVisibility(indicator, false);
            ViewUtil.setVisibility(below_tab_line, false);
        }
//        Integer type = DataUtil.getObject(getIntent(), Integer.class);
//        if(type != null){
//            switch (type){
//                case MEDIA_TYPE_IMAGE:
//                    break;
//                case MEDIA_TYPE_VIDEO:
//                    break;
//                case MEDIA_TYPE_NONE:
//                default:
//                    break;
//            }
//        }
    }

    private String filePath;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        if (resultCode == Activity.RESULT_OK) {
            if (intent != null) {
                switch (requestCode) {
                    case Constant.MEDIA_ACTION_CUT_VIDEO:
                        Serializable data = intent.getSerializableExtra(Video.class.getSimpleName());
                        if (data != null) {
                            CallBackAPI.get().goEditVideo(this, data);
                        }
                        return;
                    case Constant.MEDIA_ACTION_EDIT_VIDEO:
                        Serializable data1 = intent.getSerializableExtra(Video.class.getSimpleName());
                        Video video = JSONObject.parseObject(JSONObject.toJSONString(data1), Video.class);
                        if (video.getTopicIndex() >= 0) {
                            List<DiscoveryTopic> discoveryTopicList = DataUtil.getInstance().getCacheList(ApiKey.getVideoTopic, DiscoveryTopic.class);
                            DiscoveryTopic item = ListUtil.getItem(discoveryTopicList, video.getTopicIndex());
                            if (item != null)
                                video.setTopicId(item.getId());
                        }
                        EventBus.getDefault().post(video);
                        finish();
                        return;
                }
            }
            CameraUtil.onActivityResult(this, requestCode, filePath, new CameraCallBack() {
                @Override
                public void onGetImageSuccess(String cropFilePath) {
                    if (mAdapter.getItem(1) instanceof IRefresh) {
                        refreshData(1);
                    }
                }

                @Override
                public void onGetVideoSuccess() {
                    G.showToast("请稍等，加载视频中");
                    Observable.just(1)
                            .delay(1, TimeUnit.SECONDS)
                            .flatMap((Function<Integer, ObservableSource<MediaBean>>) integer -> Observable.just(MediaUtils.getMediaBeanWithVideo(getApplicationContext(), filePath)))
                            .subscribeOn(Schedulers.io())
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(new AbsObserver<MediaBean>() {
                                @Override
                                public void onNext(MediaBean item) {
                                    if (!ActMediaChoose.this.isDestroyed())
                                        Jump2View.getInstance().goActCutVideo(ActMediaChoose.this, Video.from(item));
                                }

                                @Override
                                public void onError(Throwable e) {
                                    if (mAdapter.getItem(0) instanceof IRefresh) {
                                        if (!ActMediaChoose.this.isDestroyed())
                                            ((IRefresh) mAdapter.getItem(0)).refreshData();
                                    }
                                }
                            });
                }

                @Override
                public void onCropImageSuccess() {
                    if (mAdapter.getItem(1) instanceof IRefresh) {
                        refreshData(1);
                    }
                }
            });
        }
    }

    private void refreshData(int position) {
        ViewUtil.delay(new AbsObserver<Integer>() {
            @Override
            public void onNext(Integer integer) {
                if (!ActMediaChoose.this.isDestroyed())
                    ((IRefresh) mAdapter.getItem(position)).refreshData();
            }
        }, 1);
    }

}
