package com.wasu.cs.ui;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.wasu.comp.videoview.IMediaListener;
import com.wasu.cs.Statistics.StatisitcsOberserver;
import com.wasu.cs.Statistics.StatisticsOberserverInterface;
import com.wasu.cs.adapter.CSTabRecyclerViewAdapter;
import com.wasu.cs.model.ChildrenData;
import com.wasu.cs.model.DemandProgram;
import com.wasu.cs.module.ChildFavModule;
import com.wasu.cs.mvp.IView.IChildrenSongView;
import com.wasu.cs.mvp.presenter.ChildrenSongPresenter;
import com.wasu.cs.utils.BitmapUtils;
import com.wasu.cs.widget.mediacontrol.MediaController;
import com.wasu.cs.widget.videoview.PlayerParams;
import com.wasu.cs.widget.videoview.WasuPlayerView;
import com.wasu.module.db.DBManage;
import com.wasu.module.log.WLog;

import java.sql.SQLException;
import java.util.List;

import basic.BuilderTypeManager.BuildType;
import basic.db.model.DBProgramChildFavorite;
import cn.com.wasu.main.IntentConstant;
import cn.com.wasu.main.IntentMap;
import cn.com.wasu.main.R;

/**
 * Created by jeepc on 2016/11/1.
 * 儿歌页
 */


public class ActivityChildrenSong extends ActivityBase implements IChildrenSongView, View.OnClickListener, StatisticsOberserverInterface, CSTabRecyclerViewAdapter.OnItemFocusChangeListener, CSTabRecyclerViewAdapter.OnItemClickListener, View.OnFocusChangeListener {
    private String TAG = "ActivityChildrenSong";
    private static final int FIRST_FOCUS_RETRY = 1;
    private static final int FOCUS_RETRY = 2;
    private static final int FOCUS = 3;
    private RecyclerView mTab_rc;
    private ViewGroup mPlayerGroup;
    private WasuPlayerView mVideoView;
    private View mArrowUp;
    private View mArrowDown;
    private ImageView mPlayerWin;
    private TextView mFav_tv;
    private View mDetail_icon;
    private View mFav_icon;

    private ChildrenSongPresenter mPresenter;
    private String mUrl = "http://120.26.137.228/?s=2002&p=sntEntryEG&k=1&v=3&stype=27&subjectId=68&bodyId=295";
    private ChildrenData mData;
    private CSTabRecyclerViewAdapter mAdapter;

    boolean isFirst = false;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case FIRST_FOCUS_RETRY:
                    setItemFocusFirst(mTab_rc, beginPosition);
                case FOCUS_RETRY:
                    setItemFocus(mTab_rc, requestPos);
                    break;
                case FOCUS:
                    setFavorite();
                    mPresenter.queryPriceToPlay(mCurrentPosition, isFirst);
                    break;
                default:
                    break;
            }
        }
    };

    private void setFavorite() {
        if (mData != null && mCurrentPosition >= 0 && mCurrentPosition < mData.getList().size()) {
            boolean b = ChildFavModule.getInstance().hasFavorite(mData.getList().get(mCurrentPosition).getId());
            if (b) {
                mFav_tv.setText("已收藏");
            } else {
                mFav_tv.setText("收藏");
            }
        }
    }

    @Override
    protected void doCreate(Bundle savedInstanceState) {
        WLog.i(TAG, "doCreate()");
        setContentView(R.layout.activity_children_song);
        init();
        parseIntent();
        mPresenter.loadData(mUrl);
    }

    private void parseIntent() {
        mUrl = getIntent().getStringExtra(IntentConstant.DATAURI.value());
    }

    Bitmap bgBitmap = null;
    @SuppressWarnings("ResourceType")
    @Override
    protected void setDefaultBg(Drawable drawable) {
        bgBitmap = BitmapUtils.readBitMapByDecodeStream(this,R.drawable.children_song_bg);
        getWindow().setBackgroundDrawable(new BitmapDrawable(getResources(), bgBitmap));

    }

    @SuppressWarnings("ResourceType")
    private void init() {
        mPlayerWin= (ImageView) findViewById(R.id.child_player_win_iv);
        Bitmap bitmap = BitmapUtils.readBitMapByDecodeResourse(this,R.drawable.children_song_player_win);
        mPlayerWin.setImageBitmap(bitmap);

        mPresenter = new ChildrenSongPresenter();
        mPresenter.attachView(this);

        mTab_rc = (RecyclerView) findViewById(R.id.tab_recyclerview);
        LinearLayoutManager layoutManager = new LinearLayoutManager(ActivityChildrenSong.this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mTab_rc.setLayoutManager(layoutManager);

        mTab_rc.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (((LinearLayoutManager) recyclerView.getLayoutManager()).findFirstVisibleItemPosition() == 0) {
                    mArrowUp.setVisibility(View.INVISIBLE);
                } else {
                    mArrowUp.setVisibility(View.VISIBLE);
                }
                if (((LinearLayoutManager) recyclerView.getLayoutManager()).findLastVisibleItemPosition() == mDataCount - 1) {
                    mArrowDown.setVisibility(View.INVISIBLE);
                } else {
                    mArrowDown.setVisibility(View.VISIBLE);
                }
            }
        });

        mTab_rc.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    if (mCurrentPosition != -1) {
                        setItemFocus(mTab_rc, mCurrentPosition);
                    }
                }
            }
        });

        mAdapter = new CSTabRecyclerViewAdapter();
        mAdapter.setOnItemFocusChangeListener(this);
        mAdapter.setOnItemClickListener(this);
        mTab_rc.setAdapter(mAdapter);

        mArrowUp = findViewById(R.id.arrow_up);
        mArrowDown = findViewById(R.id.arrow_down);

        mPlayerGroup = (ViewGroup) findViewById(R.id.player_group);
        mPlayerGroup.setOnClickListener(this);
        mVideoView = new WasuPlayerView(this, BuildType.payTypeUrl, MediaController.DISPLAY_PROMPT_EXIT_AD | MediaController.DISPLAY_CANT_OFF_SCREEN);
        mVideoView.addObserver(new StatisitcsOberserver(ActivityChildrenSong.this, mVideoView));

        Button mLast_set_btn = (Button) findViewById(R.id.last_set_btn);
        mLast_set_btn.setOnClickListener(this);
        mLast_set_btn.setOnFocusChangeListener(this);
        Button mNext_set_btn = (Button) findViewById(R.id.next_set_btn);
        mNext_set_btn.setOnClickListener(this);

        Button mDetail_btn = (Button) findViewById(R.id.detail_btn);
        mDetail_btn.setOnFocusChangeListener(this);
        mDetail_btn.setOnClickListener(this);
        mDetail_icon = findViewById(R.id.detail_icon);
        LinearLayout mFav_btn = (LinearLayout) findViewById(R.id.fav_btn);
        mFav_btn.setOnFocusChangeListener(this);
        mFav_btn.setOnClickListener(this);
        mFav_tv = (TextView) findViewById(R.id.fav_text);
        mFav_icon = findViewById(R.id.fav_icon);

        ImageView mSearch_iv = (ImageView) findViewById(R.id.search_iv);
        mSearch_iv.setOnClickListener(this);
        ImageView mFavorite_iv = (ImageView) findViewById(R.id.favorite_iv);
        mFavorite_iv.setOnClickListener(this);
    }


    View mSelV = null;//选中的view

    void setSelectView(View v) {
        v.setSelected(true);
        if (v != mSelV) {
            if (mSelV != null) {
                mSelV.setSelected(false);
            }
            mSelV = v;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        setFavorite();
        //跳到屏保状态改变 需重设
        if (mCurrentPosition != -1) {
            ViewGroup viewGroup = (ViewGroup) mTab_rc.getLayoutManager().findViewByPosition(mCurrentPosition);
            if (viewGroup != null && viewGroup.getChildAt(0) != null) {
                setSelectView(viewGroup.getChildAt(0));
            }
        }
        if (mVideoView != null) {
            mVideoView.onResume();
            if (mVideoView.isFullScreen()) {
                //跳到屏保焦点改变 需重设
                mVideoView.requestFocus();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mCurrentPosition >= 0 && mData != null && mData.getList() != null && mCurrentPosition < mData.getList().size()) {
            SharedPreferences sp = getApplicationContext().getSharedPreferences("saveId", MODE_PRIVATE);
            SharedPreferences.Editor editor = sp.edit();
            editor.putString("id", mData.getList().get(mCurrentPosition).getId());
            editor.apply();
        }

        if (mVideoView != null) {
            mVideoView.stopPlayback();
            try {
                mVideoView.removeAllViews();
                mVideoView.finalize();
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }
        if (handler != null) {
            handler.removeMessages(FIRST_FOCUS_RETRY);
            handler.removeMessages(FOCUS_RETRY);
            handler.removeMessages(FOCUS);
            handler.removeCallbacksAndMessages(null);
            handler = null;
        }
        BitmapUtils.recycleBitmap(bgBitmap);
    }

    @Override
    public void onBackPressed() {
        if (mVideoView.isFullScreen()) {
            mVideoView.toggleFullScreen();
            return;
        }
        super.onBackPressed();
    }

    int mDataCount = 0;
    int beginPosition = -1;

    @Override
    public void onDataLoaded(ChildrenData childrenData) {
        mData = childrenData;
        mDataCount = mData.getList().size();
        mAdapter.setData(mData.getList());
        mAdapter.notifyDataSetChanged();
        SharedPreferences sp = getSharedPreferences("saveId", MODE_PRIVATE);
        String id = sp.getString("id", "");
        beginPosition = getTheIdPosition(childrenData, id);
        if (beginPosition == -1) {
            beginPosition = (int) (childrenData.getList().size() * Math.random());
        }
        setItemFocusFirst(mTab_rc, beginPosition);
    }

    int getTheIdPosition(ChildrenData childrenData, String id) {
        if (childrenData != null && childrenData.getList() != null) {
            List<ChildrenData.ListBean> list = childrenData.getList();
            for (int i = 0; i < list.size(); i++) {
                if (list.get(i).getId().equals(id)) {
                    return i;
                }
            }
        }
        return -1;
    }

    @Override
    public void showErrorExitDlg() {

    }

    boolean tag = false;//mVideoView设置锚tag
    int mCurrentPosition = -1;//当前播放的position
    DemandProgram mDemandProgram;


    int requestPos = -1;

    //设置请求焦点
    private void setItemFocus(RecyclerView recyclerView, int pos) {
        isFirst = false;
        recyclerView.getLayoutManager().scrollToPosition(pos);
        requestPos = pos;
        View view = recyclerView.getLayoutManager().findViewByPosition(pos);
        if (view != null) {
            view.requestFocus();
        } else {
            handler.sendEmptyMessageDelayed(FOCUS_RETRY, 100);
        }
    }

    //设置请求焦点
    private void setItemFocusFirst(RecyclerView recyclerView, int pos) {
        isFirst = true;
        recyclerView.getLayoutManager().scrollToPosition(pos);
        View view = recyclerView.getLayoutManager().findViewByPosition(pos);
        if (view != null) {
            view.requestFocus();
        } else {
            handler.sendEmptyMessageDelayed(FIRST_FOCUS_RETRY, 100);
        }
    }

    //播放视频
    @Override
    public void playVideo(DemandProgram demandProgram, int position) {
        //避免异步回调导致播放错误资产
        if(position!=mCurrentPosition){
            return;
        }
        mDemandProgram = demandProgram;
        if (demandProgram == null || position == -1) {
            return;
        }
        mDemandProgram = demandProgram;
        if (mVideoView == null) {
            mVideoView = new WasuPlayerView(this, BuildType.payTypeUrl, MediaController.DISPLAY_PROMPT_EXIT_AD | MediaController.DISPLAY_CANT_OFF_SCREEN);
        }
        if (!tag) {
            mVideoView.setAnchorView(mPlayerGroup, this);
            tag = true;
            final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams((int) getResources().getDimension(R.dimen.d_848dp),
                    (int) getResources().getDimension(R.dimen.d_484dp));
            layoutParams.setMargins((int) getResources().getDimension(R.dimen.d_2dp), (int) getResources().getDimension(R.dimen.d_26dp), 0, 0);
            mVideoView.setPlayerWindow(R.drawable.children_song_player_win_unfocused, layoutParams);
            mPlayerGroup.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                @Override
                public void onFocusChange(View v, boolean hasFocus) {
                    if (hasFocus) {
                        ViewGroup viewGroup = (ViewGroup) mTab_rc.getLayoutManager().findViewByPosition(mCurrentPosition);
                        if (viewGroup != null && viewGroup.getChildAt(0) != null) {
                            setSelectView(viewGroup.getChildAt(0));
                        }
                        mVideoView.setPlayerWindow(R.drawable.children_song_player_win_focused, layoutParams);
                    } else {
                        mVideoView.setPlayerWindow(R.drawable.children_song_player_win_unfocused, layoutParams);
                    }
                }
            });
            if (mPlayerWin != null && mPlayerWin.getParent() != null) {
                mPlayerWin.setImageBitmap(null);
                ((ViewGroup) mPlayerWin.getParent()).removeView(mPlayerWin);
            }
        }
        PlayerParams params = new PlayerParams();
        params.setAssetInfo(demandProgram);
        mVideoView.play(params);

    }

    @Override
    public boolean uiIsFinishing() {
        return isFinishing();
    }

    @Override
    public void onPriceChange(final int pos, int fee) {
        mData.getList().get(pos).setFee(fee);
        mAdapter.setData(mData.getList());
        mAdapter.notifyDataSetChanged();

    }

    @Override
    public void playNextVideo() {
        if (mCurrentPosition == mDataCount - 1) {
            mCurrentPosition = 0;
            mPresenter.queryPriceToPlay(mCurrentPosition, false);
            setItemFocus(mTab_rc, mCurrentPosition);
        } else {
            mPresenter.queryPriceToPlay(++mCurrentPosition, false);
            setItemFocus(mTab_rc, mCurrentPosition);
        }
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.last_set_btn:
                if (mDemandProgram != null) {
                    int curPlayIndex = mDemandProgram.getCurPlayIndex();
                    if (curPlayIndex == 1) {
                        Toast.makeText(ActivityChildrenSong.this, "当前是第一集", Toast.LENGTH_LONG).show();
                    } else {
                        play(curPlayIndex - 1);
                    }
                }
                break;
            case R.id.next_set_btn:
                if (mDemandProgram != null) {
                    int curPlayIndex = mDemandProgram.getCurPlayIndex();
                    if (curPlayIndex == mDemandProgram.getNowItem()) {
                        Toast.makeText(ActivityChildrenSong.this, "当前是最后一集", Toast.LENGTH_LONG).show();
                    } else {
                        play(curPlayIndex + 1);
                    }
                }
                break;
            case R.id.detail_btn:
                if (mDemandProgram != null) {
                    Intent intent = new Intent();
                    IntentMap.startIntent(ActivityChildrenSong.this, intent, null, mDemandProgram.getDetailUrl(), ActivityChildrenDetail.class);
                }
                break;
            case R.id.fav_btn:
                if (mDemandProgram != null) {
                    boolean b = ChildFavModule.getInstance().hasFavorite(mData.getList().get(mCurrentPosition).getId());
                    try {
                        if (b) {

                            DBManage.deleteBy(DBProgramChildFavorite.class, "programId", mDemandProgram.getId());
                            mFav_tv.setText("收藏");
                            Toast.makeText(ActivityChildrenSong.this, "已收藏，点击取消！", Toast.LENGTH_SHORT);

                        } else {
                            DBProgramChildFavorite favorite = new DBProgramChildFavorite();
                            favorite.programId = Integer.parseInt(mDemandProgram.getId());
                            favorite.domain = "";
                            favorite.programPic = mDemandProgram.getPicUrl();
                            favorite.programName = mDemandProgram.getTitle();
                            favorite.detailUrl = mDemandProgram.getDetailUrl();
                            favorite.playUrl = "";
                            favorite.showType = mDemandProgram.getAssetType();// 0非影视剧
                            favorite.preUpdateSeries = mDemandProgram.getNowItem();
                            favorite.updateSeries = mDemandProgram.getNowItem();
                            favorite.totalSeries = mDemandProgram.getItemNum();
                            favorite.savefavoritetime = System.currentTimeMillis();
                            favorite.insertOrUpdate();
                            mFav_tv.setText("已收藏");
                            Toast.makeText(ActivityChildrenSong.this, "已取消收藏，点击收藏！", Toast.LENGTH_SHORT);
                        }
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                } else {
                    Toast.makeText(ActivityChildrenSong.this, "请稍候再试！", Toast.LENGTH_LONG).show();
                }
                break;
            case R.id.search_iv:
                if (mData != null && !TextUtils.isEmpty(mData.getSearchUrl())) {
                    IntentMap.startIntent(ActivityChildrenSong.this, null, mData.getLayout(), mData.getSearchUrl(), null);
                }
                break;
            case R.id.favorite_iv:
                Intent intent = new Intent();
                IntentMap.startIntent(ActivityChildrenSong.this, intent, null, null, ActivityChildrenFav.class);
                break;
            case R.id.player_group:
                mVideoView.toggleFullScreen();
                break;
            default:
                break;
        }
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        switch (v.getId()) {
            case R.id.last_set_btn:
                if (hasFocus) {
                    ViewGroup viewGroup = (ViewGroup) mTab_rc.getLayoutManager().findViewByPosition(mCurrentPosition);
                    if (viewGroup != null && viewGroup.getChildAt(0) != null) {
                        setSelectView(viewGroup.getChildAt(0));
                    }
                }
                break;
            case R.id.detail_btn:
                if (hasFocus) {
                    mDetail_icon.setSelected(true);
                } else {
                    mDetail_icon.setSelected(false);
                }
                break;
            case R.id.fav_btn:
                if (hasFocus) {
                    mFav_icon.setSelected(true);
                    mFav_tv.setSelected(true);
                } else {
                    mFav_icon.setSelected(false);
                    mFav_tv.setSelected(false);
                }
                break;
            default:
                break;
        }
    }


    private void play(int index) {
        if (mVideoView != null) {
            if (mVideoView.isPlaying()) {
                mVideoView.stopPlayback();
            }
            mDemandProgram.setCurPlayIndex(index);
            PlayerParams params = new PlayerParams();
            params.setAssetInfo(mDemandProgram);
            params.setDomain(BuildType.HTTP_DOMAIN);
            mVideoView.play(params);

        }
    }

    @Override
    public void onItemFocusChange(int pos, boolean hasfocus) {
        if (hasfocus) {
            if (mCurrentPosition != pos) {
                mCurrentPosition = pos;
                handler.removeMessages(FOCUS);
                handler.sendEmptyMessageDelayed(FOCUS, 300);
            }
        }

    }


    @Override
    public void onItemClick(int pos) {
        IntentMap.startIntent(ActivityChildrenSong.this, null, null, mData.getList().get(pos).getJsonUrl(), ActivityChildrenDetail.class);
    }

    /**
     * IMediaListener
     */
    @Override
    public void onStart(MediaPlayer mediaPlayer) {

    }

    @Override
    public void onPreparing(MediaPlayer mediaPlayer) {

    }

    @Override
    public void onPrepareComplete(MediaPlayer mediaPlayer) {

    }

    @Override
    public void onSeeking(MediaPlayer mediaPlayer) {

    }

    @Override
    public void onSeekComplete(MediaPlayer mediaPlayer) {

    }

    @Override
    public void onProgress(int i, int i1, int i2) {

    }

    @Override
    public void onPause(MediaPlayer mediaPlayer) {

    }

    @Override
    public void onResume(MediaPlayer mediaPlayer) {

    }

    @Override
    public void onStop(MediaPlayer mediaPlayer) {

    }

    @Override
    public void onCompletion(MediaPlayer mediaPlayer) {
        if (mVideoView.isLastSeriesFinish()) {
            playNextVideo();
        }
    }

    @Override
    public void onError(MediaPlayer mediaPlayer, int i, int i1) {

    }

    @Override
    public void onInfo(MediaPlayer mediaPlayer, int i, int i1) {

    }

    @Override
    public void onStatusChanged(MediaPlayer mediaPlayer, int i) {

    }

    @Override
    public void onAdStatusChanged(int i, int i1) {

    }

    @Override
    public void onWasuError(int i, String s) {
        switch (i) {
            case IMediaListener.WASU_ERROR_AUTH:
            case IMediaListener.WASU_ERROR_PAY:
                playNextVideo();
                break;
            default:
                break;
        }
    }

    @Override
    public void onWasuPlayLimit(int i, String s) {

    }


}

