package com.wasu.cs.mvp;

import android.content.Context;
import android.media.MediaPlayer;
import android.widget.Toast;

import com.wasu.authsdk.AuthSDK;
import com.wasu.comp.videoview.IMediaListener;
import com.wasu.cs.model.DemandProgram;
import com.wasu.cs.module.FavAndHisModule;
import com.wasu.cs.mvp.IView.DetailView;
import com.wasu.cs.mvp.presenter.DetailLogic;
import com.wasu.cs.ui.ActivityDetail;
import com.wasu.cs.widget.videoview.WasuPlayerView;
import com.wasu.module.log.WLog;
import com.wasu.statistics.PlayInfo;
import com.wasu.statistics.WasuStatistics;

import java.util.ArrayList;

import basic.BuilderTypeManager.BuildType;
import cn.com.wasu.main.AppUtil;

/**
 * Created by hudong on 16-6-30.
 */
public class DetailPlayerOberserver implements IMediaListener {

    private static final String TAG = "DetailPlayerOberserver";
    WasuPlayerView mVideoView;
    Context context;
    DetailLogic detailLogic;
    DemandProgram mAsset;
    private String cdnUrl = "";//保存当前播放的cdn的码率

    public DetailPlayerOberserver(Context context, DemandProgram mAsset, DetailLogic detailLogic, WasuPlayerView mVideoView) {
        this.context = context;
        this.mVideoView = mVideoView;
        this.detailLogic = detailLogic;
        this.mAsset = mAsset;
    }

    @Override
    public void onWasuPlayLimit(int arg0, String arg1) {
        WLog.i(TAG, "onWasuPlayLimit arg0=" + arg0 + ",arg1=" + arg1);
        if (arg0 == IMediaListener.WASU_PLAY_FREE) {//支付成功
            detailLogic.queryPrice(false);
            if (!mVideoView.isFullScreen())//小屏状态才去请求下焦点
                ((ActivityDetail) context).mPlayerGroup.requestFocus();
        }
    }

    @Override
    public void onWasuError(int arg0, String arg1) {
        WLog.i(TAG, "onError");
        if (mAsset.getAssetFrom() == 91) {//由于双方不同步，搜狐资产可能已经下线给出对应的提示
            if (arg0 == IMediaListener.WASU_ERROR_PAY) {
                Toast.makeText(context, "请先支付后再观看", Toast.LENGTH_SHORT).show();
            } else if (arg0 == IMediaListener.WASU_ERROR_AUTH){
                Toast.makeText(context,"用户登录失败",Toast.LENGTH_SHORT).show();
            }else {
                Toast.makeText(context, "资产可能已下线或网络不佳", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(context, arg1, Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onStop(MediaPlayer arg0) {
        if (mAsset == null) {
            return;
        }
        playend(mVideoView.getCurrentPosition(), mVideoView.getDuration());
    }

    private void playend(int currentpositon, int duration) {
        if (AppUtil.playInfo != null && AppUtil.playInfo.mVideoId != null && mAsset != null && AppUtil.playInfo.mVideoId.equals(mAsset.getId())) {//规避进入多层详情页后，后台的详情页会回收播放器资源，多发送一次统计数据
            SendPlayEnd(currentpositon, duration);
        }
    }

    @Override
    public void onStatusChanged(MediaPlayer arg0, int arg1) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onStart(MediaPlayer arg0) {
        if (mVideoView != null) {
            cdnUrl = mVideoView.getRealUrl();
        }
        MarkPlayInfo();
    }

    @Override
    public void onSeeking(MediaPlayer arg0) {
        WasuStatistics.getInstance().seekBegin();
    }

    @Override
    public void onSeekComplete(MediaPlayer arg0) {
        WasuStatistics.getInstance().seekEnd();
    }

    @Override
    public void onResume(MediaPlayer arg0) {
        WasuStatistics.getInstance().onResume();
    }

    @Override
    public void onProgress(int arg0, int arg1, int arg2) {

    }

    @Override
    public void onPreparing(MediaPlayer arg0) {
        WasuStatistics.getInstance().prepareBegin();
    }

    @Override
    public void onPrepareComplete(MediaPlayer arg0) {
        WasuStatistics.getInstance().prepareEnd();
    }

    @Override
    public void onPause(MediaPlayer arg0) {
        WasuStatistics.getInstance().onPause();
    }

    @Override
    public void onInfo(MediaPlayer arg0, int arg1, int arg2) {
        if (arg1 == MediaPlayer.MEDIA_INFO_BUFFERING_START) {
            WasuStatistics.getInstance().bufferBegin();
        } else if (arg1 == MediaPlayer.MEDIA_INFO_BUFFERING_END) {
            WasuStatistics.getInstance().bufferEnd();
        } else if (arg1 == WasuPlayerView.MSG_ASSET_CHANGED) {
            refreshUi();
        }
    }

    private void refreshUi() {
        ((DetailView) context).loadAssetDetailSuccess(mAsset);
        ((DetailView) context).updateFavoriteUi(FavAndHisModule.getInstance().hasFavorite(mAsset.getId()));
        detailLogic.queryPrice(false);
    }

    @Override
    public void onError(MediaPlayer arg0, int arg1, int arg2) {
        WLog.i(TAG, "onError");
    }

    @Override
    public void onCompletion(MediaPlayer arg0) {
        playend(mVideoView.getCurrentPosition(), mVideoView.getDuration());
        if (mAsset.getAssetType() == DemandProgram.SHOWTYPE_MOVIE) {
            if (mVideoView.isFullScreen()) {
                mVideoView.toggleFullScreen();
            }
        } else if (mAsset.getAssetType() == DemandProgram.SHOWTYPE_TV_SERIES) {
            if (getHistoryIndex(mAsset.getCurPlayIndex()) == mAsset.getTotal() - 1 && mVideoView.isLastSeriesFinish()) {
            }
        }
    }

    private int getHistoryIndex(int mHistory_episode) {
        if (mAsset.getDetailSeriesSet() == null) {
            return -1;
        }
        ArrayList<Integer> seriesList = mAsset.getDetailSeriesSet().getSerieslist();
        int index = 0;
        for (index = 0; index < seriesList.size(); index++) {
            if (mHistory_episode == seriesList.get(index)) {
                return index;
            }
        }
        return -1;
    }

    @Override
    public void onAdStatusChanged(int arg0, int arg1) {
        // TODO Auto-generated method stub

    }

    // 获取vip信息
    private String checkIsVip() {
        String isvip= AuthSDK.getInstance().getValue("vipState");
        return isvip.isEmpty()?"0":isvip;
    }

    // 记录PlayInfo
    public void MarkPlayInfo(){
        PlayInfo playInfo = new PlayInfo(mAsset.getId(), mAsset.getTitle(), cdnUrl, "",
                mAsset.getPpv(), BuildType.SITE_ID, "", mAsset.getPriceInfo().getPrice() + "",
                mAsset.getAssetTypeText(), (mAsset.getCurPlayIndex()) + "", detailLogic.getAdFree() + "", "0", mAsset.getContentChannel(),
                "begin", mAsset.getPriceInfo().getOriginalPrice()+"", checkIsVip());
        WasuStatistics.getInstance().playBegin(playInfo, ((DetailView) context).getEnter());
        AppUtil.playInfo = playInfo;
    }

    // 发送播放器结束时的统计
    public void SendPlayEnd(int currentpositon, int duration){
        // 调起播放结束的统计
        WasuStatistics.getInstance().use(mAsset.getId(), mVideoView.getCurrentPosition()+"");

        WasuStatistics.getInstance().setPlayinfo(new PlayInfo(mAsset.getId(), mAsset.getTitle(), cdnUrl, "",
                mAsset.getPpv(), BuildType.SITE_ID, "", mAsset.getPriceInfo().getPrice() + "",
                mAsset.getAssetTypeText(), (AppUtil.playInfo.index) + "", detailLogic.getAdFree() + "", "0", mAsset.getContentChannel(), "begin", mAsset.getPriceInfo().getOriginalPrice()+"", checkIsVip()), ((DetailView) context).getEnter());
        WasuStatistics.getInstance().playEnd(currentpositon, duration);
        AppUtil.playInfo = new PlayInfo(); // 重置，防止支付跳出后再一次上传
    }
}


