package com.wasu.cs.Statistics;

import android.media.MediaPlayer;

import com.wasu.authsdk.AuthListener;
import com.wasu.authsdk.AuthSDK;
import com.wasu.authsdk.IAuthInterface;
import com.wasu.common.WError;
import com.wasu.comp.videoview.IMediaListener;
import com.wasu.cs.model.DemandProgram;
import com.wasu.cs.widget.videoview.WasuPlayerView;
import com.wasu.module.log.WLog;
import com.wasu.statistics.PlayInfo;
import com.wasu.statistics.WasuStatistics;

import org.json.JSONObject;

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


/**
 * 通用的统计前置观察者
 * 适用于集成wasuPlayerView
 *
 * @author chenliang
 *         20161205
 */

public class StatisitcsOberserver implements IMediaListener {
    private String TAG = "StatisitcsOberserver";

    private StatisticsOberserverInterface mInterface; // 接口
    private WasuStatistics mStatistics; // 统计实例
    private WasuPlayerView mVideoView;

    private int adFree = 0; // 是否免广告
    private PlayInfo mPlayInfo;

    /************************************构造方法***************************************************/
    /**
     * 不带回调版本
     * 可以不继承StatisticsOberserverInterface
     */
    public StatisitcsOberserver(WasuPlayerView VideoView) {
        mStatistics = WasuStatistics.getInstance();
        mVideoView = VideoView;
        adFreeQuery();
    }


    /**
     * 带回调版本
     * 需要统计的播放器事件activity 请先继承StatisticsOberserverInterface 以便控制生命周期
     */
    public StatisitcsOberserver(StatisticsOberserverInterface oberserverInterface, WasuPlayerView VideoView) {
        mInterface = oberserverInterface;
        mVideoView = VideoView;
        mStatistics = WasuStatistics.getInstance();
        adFreeQuery();
    }

    /************************************** 生命周期************************************************/
    @Override
    public void onStart(MediaPlayer mediaPlayer) {
        WLog.i(TAG, "onStart");
        mPlayInfo = createPlayInfo();
        if (mPlayInfo == null){
            mStatistics.playBegin(new PlayInfo(), AppUtil.playEnter);
        }else {
            mStatistics.playBegin(mPlayInfo, AppUtil.playEnter);
        }

        if (mInterface != null) {
            mInterface.onStart(mediaPlayer);
        }
    }

    @Override
    public void onPreparing(MediaPlayer mediaPlayer) {
        WLog.i(TAG, "onPreparing");
        mStatistics.prepareBegin();

        if (mInterface != null) {
            mInterface.onPreparing(mediaPlayer);
        }
    }

    @Override
    public void onPrepareComplete(MediaPlayer mediaPlayer) {
        WLog.i(TAG, "onPrepareComplete");
        mStatistics.prepareEnd();

        if (mInterface != null) {
            mInterface.onPrepareComplete(mediaPlayer);
        }
    }

    @Override
    public void onSeeking(MediaPlayer mediaPlayer) {
        WLog.i(TAG, "onSeeking");
        mStatistics.seekBegin();

        if (mInterface != null) {
            mInterface.onSeeking(mediaPlayer);
        }
    }

    @Override
    public void onSeekComplete(MediaPlayer mediaPlayer) {
        WLog.i(TAG, "onSeekComplete");
        mStatistics.seekEnd();

        if (mInterface != null) {
            mInterface.onSeekComplete(mediaPlayer);
        }
    }

    @Override
    public void onProgress(int i, int i1, int i2) {
        if (mInterface != null) {
            mInterface.onProgress(i, i1, i2);
        }
    }

    @Override
    public void onPause(MediaPlayer mediaPlayer) {
        WLog.i(TAG, "onPause");
        mStatistics.onPause();

        if (mInterface != null) {
            mInterface.onPause(mediaPlayer);
        }
    }

    @Override
    public void onResume(MediaPlayer mediaPlayer) {
        WLog.i(TAG, "onResume");
        mStatistics.onResume();

        if (mInterface != null) {
            mInterface.onResume(mediaPlayer);
        }
    }

    @Override
    public void onStop(MediaPlayer mediaPlayer) {
        WLog.i(TAG, "onStop");
        playEnd();

        if (mInterface != null) {
            mInterface.onStop(mediaPlayer);
        }
    }

    @Override
    public void onCompletion(MediaPlayer mediaPlayer) {
        playEnd();

        if (mInterface != null) {
            mInterface.onCompletion(mediaPlayer);
        }
    }

    @Override
    public void onError(MediaPlayer mediaPlayer, int i, int i1) {
        if (mInterface != null) {
            mInterface.onError(mediaPlayer, i, i1);
        }
    }

    @Override
    public void onInfo(MediaPlayer mediaPlayer, int i, int i1) {
        if (i == MediaPlayer.MEDIA_INFO_BUFFERING_START) {
            WasuStatistics.getInstance().bufferBegin();
        } else if (i == MediaPlayer.MEDIA_INFO_BUFFERING_END) {
            WasuStatistics.getInstance().bufferEnd();
        }

        if (mInterface != null) {
            mInterface.onInfo(mediaPlayer, i, i1);
        }
    }

    @Override
    public void onStatusChanged(MediaPlayer mediaPlayer, int i) {
        if (mInterface != null) {
            mInterface.onStatusChanged(mediaPlayer, i);
        }
    }

    @Override
    public void onAdStatusChanged(int i, int i1) {
        if (mInterface != null) {
            mInterface.onAdStatusChanged(i, i1);
        }
    }

    @Override
    public void onWasuError(int i, String s) {
        if (mInterface != null) {
            mInterface.onWasuError(i, s);
        }
    }

    @Override
    public void onWasuPlayLimit(int i, String s) {
        if (mInterface != null) {
            mInterface.onWasuPlayLimit(i, s);
        }
    }

    /******************************************************************************************/
    /**
     * 统一发送播放结束统计
     * */
    private void playEnd() {
        if (mVideoView != null) {
            if (mPlayInfo == null){ // 如果播放前获取失败
                mPlayInfo = createPlayInfo();
            }

            if (mPlayInfo == null){ // 重试仍然无法获取playinfo
                mPlayInfo = new PlayInfo();
            }

            mStatistics.addPageElem(mPlayInfo);
            mStatistics.setPlayinfo(mPlayInfo, AppUtil.playEnter); // 更新playinfo
            mStatistics.playEnd(mVideoView.getCurrentPosition(), mVideoView.getDuration());
        }
    }

    /**
     * playinfo（完整16参数）
     * 1String mVideoId,2String mVideoName,3String mVideoUrl,4String mVideoBit,5String mVideoPpv,
     6String mVideoSite,(默认)
     7String traceid,8String price,9String assetType,10String index,11String adfree,
     12String cdnorp2p,（默认）
     13String channel,
     14String status,（默认）
     15String markprice,
     16String isvip （默认）
     **/
    private PlayInfo createPlayInfo(){
        if (mVideoView != null && mVideoView.getAssetInfo() != null) {
            DemandProgram d = mVideoView.getAssetInfo();

            PlayInfo p = new PlayInfo(d.getId(), d.getTitle(), mVideoView.getRealUrl(),
                    mVideoView.getBitrate()+"", d.getPpv(), BuildType.SITE_ID, ""/**traceid*/,
                    d.getPriceInfo().getPrice()+"", d.getAssetTypeText(), d.getCurPlayIndex()+"", adFree+"", "0",
                    d.getContentChannel(), "begin",  d.getPriceInfo().getOriginalPrice()+"", checkIsVip());

            return p;

        }else {
            WLog.e(TAG, "统计观察者不允许传入播放器为null!");
            return null;
        }
    }

    /**
     *
     * 查询是否免广告
     * */
    public void adFreeQuery() {
        if (AuthSDK.getInstance().getValue(IAuthInterface.KEY_USERKEY).isEmpty()) {//未登录用户不能调免广告查询接口
            return ;
        }

        AuthSDK.getInstance().verifyUserIsAdFree(new AuthListener() {
            @Override
            public void result(int ret, String extra, Object retData) {
                if (ret != WError.ERROR_NONE) {
                    WLog.e(TAG, "adFreeQuery verifyUserIsAdFree fail:" + extra);
                } else {
                    try {
                        JSONObject root = new JSONObject(new String((byte[]) retData, "utf-8"));
                        adFree = root.optInt("isFree");
                        if (adFree != 1) {
                            adFree = 0;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

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