package com.wasu.cs.widget.videoview;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaPlayer;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.drawee.drawable.ScalingUtils;
import com.facebook.drawee.view.SimpleDraweeView;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.wasu.authsdk.AuthListener;
import com.wasu.authsdk.AuthSDK;
import com.wasu.authsdk.entity.PriceInfo;
import com.wasu.common.WError;
import com.wasu.comp.videoview.IMediaControl;
import com.wasu.comp.videoview.IMediaListener;
import com.wasu.cs.model.ConfigData;
import com.wasu.cs.model.DemandProgram;
import com.wasu.cs.ui.ActivityPlayer;
import com.wasu.cs.utils.BitmapUtils;
import com.wasu.frescoimagefetchermodule.FrescoImageFetcherModule;
import com.wasu.module.datafetch.DataFetchListener;
import com.wasu.module.datafetch.DataFetchModule;
import com.wasu.module.log.WLog;

import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import cn.com.wasu.main.BuildConfig;
import cn.com.wasu.main.ChannelFlavor;
import cn.com.wasu.main.Common;
import cn.com.wasu.main.R;

/**
 * 播放器蒙版
 * Created by zhangrm on 16-3-15.
 */
public class PlayerMask extends FrameLayout implements IMediaListener {

    private static final String TAG = "PlayerMask";
    private DemandProgram assetInfo;
    private IMediaControl player;

    private boolean isFullScreen;

    public DemandProgram getAssetInfo() {
        return assetInfo;
    }

    public void setAssetInfo(DemandProgram assetInfo) {
        this.assetInfo = assetInfo;
    }

    public IMediaControl getPlayer() {
        return player;
    }

    public void setPlayer(IMediaControl player) {
        this.player = player;
    }

    private SimpleDraweeView loadingView; // 播放器蒙版背景
    private boolean mLoViewFromService = false; // 背景图片是否由后台下发
    private Bitmap deFaultBackGround; // 加载的默认背景图
    private int bigView = R.drawable.backview, smallView = R.drawable.backview; // 设定大小图背景
    private ImageView shelterView;
    private TextView restTime;
    private boolean mIsToastShowing = false; // 避免同时多次提示
    private Runnable mToastRun;
    Context context;
    public PlayerMask(Context context) {
        super(context);
        this.context = context;
        setFocusable(false);
        setFocusableInTouchMode(false);
        setBackgroundColor(Color.TRANSPARENT);

        init(context);
    }

    private void init(Context context) {
        loadingView = new SimpleDraweeView(context);
        setLoadingViewBackground(context);
        loadingView.getHierarchy().setActualImageScaleType(ScalingUtils.ScaleType.FIT_XY);
        loadingView.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));

        if (loadingView.getParent() == null) {
            addView(loadingView);
        }
        shelterView = new ImageView(context);
        shelterView.setBackgroundResource(R.drawable.player_wasu_shelter);

        restTime = new TextView(context);
        restTime.setBackgroundColor(Color.parseColor("#80000000"));
        restTime.setSingleLine(true);
        restTime.setTextColor(Color.WHITE);
        restTime.setGravity(Gravity.CENTER);
        restTime.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimensionPixelSize(R.dimen.d_16dp));
        FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT);
        layoutParams.gravity = Gravity.BOTTOM;
        restTime.setLayoutParams(layoutParams);

        mToastRun = new Runnable() {
            @Override
            public void run() {
                mIsToastShowing = false;
            }
        };
    }

    private void setLoadingViewBackground(final Context context) {
        if (context instanceof ActivityPlayer){
            // 默认大屏
            deFaultBackGround = BitmapUtils.readBitMapByDecodeStream(context, bigView, Bitmap.Config.ARGB_8888);
        }else {
            // 初始小屏
            deFaultBackGround = BitmapUtils.readBitMapByDecodeStream(context, smallView, Bitmap.Config.ARGB_8888);
        }

        loadingView.setBackgroundDrawable(new BitmapDrawable(this.context.getResources(), deFaultBackGround));
        SharedPreferences sp = getContext().getSharedPreferences("configData", Context.MODE_PRIVATE);
        String url=sp.getString("playCover","");
        if(url!=null){
            mLoViewFromService = true;
            FrescoImageFetcherModule.getInstance().attachImage(url,loadingView);
            return;
        }else{
            loadingView.setBackgroundDrawable(new BitmapDrawable(this.context.getResources(), deFaultBackGround));
        }
        DataFetchModule.getInstance().fetchJsonGet(Common.CONFIG_URL, new DataFetchListener.JsonListener() {

            @Override
            public void onJsonGet(int retcode, String extraMsg,JSONObject jsondata) {
                if(retcode != 0){
                    WLog.e(TAG, "fetch config data failure");
                }else{
                    try {
                        Gson gson = new Gson();
                        ConfigData configData = gson.fromJson(jsondata.toString(),ConfigData.class);
                        if(!configData.getData().getPlayCoverPicUrl().isEmpty()){
                            mLoViewFromService = true;
                            FrescoImageFetcherModule.getInstance().attachImage(configData.getData().getPlayCoverPicUrl(), loadingView);
                        }else{
                            loadingView.setBackgroundDrawable(new BitmapDrawable(context.getResources(), deFaultBackGround));
                        }
                        saveConfigData(configData);
                    } catch (JsonSyntaxException e) {
                        e.printStackTrace();
                        WLog.e(TAG, "Json data error");
                    }
                }
            }
        });
    }
    /**
     * 把角标信息存储在SharedPreferences中
     * danxingxi
     */
    @SuppressLint("CommitPrefEdits")
    public void saveConfigData(ConfigData configData){
        SharedPreferences  sp = getContext().getSharedPreferences("configData", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.clear();
        if(configData.getData().getCornerMarks().size()>0){
            for(ConfigData.DataEntity.CornerMarksEntity cornerMark : configData.getData().getCornerMarks()){
                editor.putString(cornerMark.getCmark(), cornerMark.getPicUrl());
            }
        }
        editor.putString("playCover", configData.getData().getPlayCoverPicUrl());
        editor.commit();
    }
    private void invalidateShelterView() {
        post(new Runnable() {
            @Override
            public void run() {
                int width = getMeasuredWidth();
                int height = getMeasuredHeight();

                FrameLayout.LayoutParams lp;
                if(assetInfo.getAssetFrom()==93){
                    lp = new FrameLayout.LayoutParams((int) (width * 0.16f), (int) (height * 0.12f));
                    lp.gravity = Gravity.RIGHT;
                    lp.rightMargin = (int) (width * 0.04f);
                }else{
                    lp = new FrameLayout.LayoutParams((int) (width * 0.14f), (int) (height * 0.1f));
                    lp.leftMargin = (int) (width * 0.03f);
                }
                lp.topMargin = (int) (height * 0.04f);
                shelterView.setLayoutParams(lp);

                if (shelterView.getParent() == null) {
                    addView(shelterView);
                }
            }
        });
    }

    private void invalidateRestTime() {
        if (assetInfo == null || isFullScreen || mIsToastShowing) {
            return;
        }
        mIsToastShowing = true;
        postDelayed(mToastRun, 3000);

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("resourceId", assetInfo.getId());
        params.put("resourceName", assetInfo.getTitle());
        params.put("orderType", 0);

        AuthSDK.getInstance().queryPrice(params, new AuthListener() {
            @Override
            public void result(int ret, String extra, Object retData) {
                if (ret == WError.ERROR_NONE) {
                    PriceInfo price = (PriceInfo) retData;
                    double originalPrice = price.getOriginalPrice();
                    long time = price.getRestTime();

                    if (price.getPrice() == 0 && originalPrice > 0) {
                        if (originalPrice == 99999) {
                            restTime.setText("");

                            View layout = LayoutInflater.from(context).inflate(R.layout.toast_layout, null);
                            TextView tv = (TextView) layout.findViewById(R.id.text);
                            tv.setText("VIP到期时间：" + calTime(time));
                            Toast t = new Toast(getContext());
                            t.setGravity(Gravity.TOP|Gravity.CENTER_HORIZONTAL, 0, 0);
                            t.setView(layout);
                            t.show();

                        } else {
                            restTime.setText("");

                            View layout = LayoutInflater.from(context).inflate(R.layout.toast_layout, null);
                            TextView tv = (TextView) layout.findViewById(R.id.text);
                            tv.setText("免费观看到期时间：" + calTime(time));
                            Toast t = new Toast(getContext());
                            t.setGravity(Gravity.TOP|Gravity.CENTER_HORIZONTAL|Gravity.FILL_HORIZONTAL, 0, 0);
                            t.setView(layout);
                            t.show();
                        }

                        if (restTime.getParent() == null) {
                            addView(restTime);
                            postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    removeView(restTime);
                                }
                            },5000);
                        }
                    } else if (price.getPrice() > 0) {
                        restTime.setText("");
                        if (restTime.getParent() != null) {
                            removeView(restTime);
                        }
                    }
                }
            }
        });
    }

    private String calTime(long time) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒", Locale.CHINESE);
        return format.format(new Date(System.currentTimeMillis() + time * 1000));
    }

    public void refresh() {
        if (!isFullScreen) {
            invalidateRestTime();
        }
    }

    /**
     * 大小屏切换
     * */
    public void handleFullScreen(boolean isFullScreen) {
        this.isFullScreen = isFullScreen;
        changeLoadingView();

        if (player != null && player.isInPlaybackState() && assetInfo != null && (assetInfo.getAssetFrom() == 91||assetInfo.getAssetFrom() == 93)) {
            invalidateShelterView();
        }

        if (!isFullScreen) {
            invalidateRestTime();
        } else if (restTime.getParent() != null) {
            removeView(restTime);
        }
    }

    /**
     * 大小屏切换时更换播放器蒙版图
     * */
    private void changeLoadingView(){
        if (!mLoViewFromService){
            if (isFullScreen){
                // 大屏图
                deFaultBackGround = BitmapUtils.readBitMapByDecodeStream(context, bigView, Bitmap.Config.ARGB_8888);
                loadingView.setBackgroundDrawable(new BitmapDrawable(this.context.getResources(), deFaultBackGround));
            }else {
                // 小屏图
                deFaultBackGround = BitmapUtils.readBitMapByDecodeStream(context, smallView, Bitmap.Config.ARGB_8888);
                loadingView.setBackgroundDrawable(new BitmapDrawable(this.context.getResources(), deFaultBackGround));
            }
        }
    }

    @Override
    public void onStart(MediaPlayer mediaPlayer) {
        if (loadingView.getParent() == null) {
            addView(loadingView);
        }
    }

    @Override
    public void onPreparing(MediaPlayer mediaPlayer) {
        if (shelterView.getParent() != null) {
            removeView(shelterView);
        }
    }

    @Override
    public void onPrepareComplete(MediaPlayer mediaPlayer) {
        if (loadingView.getParent() != null) {
            removeView(loadingView);
        }

        if (shelterView.getParent() == null && assetInfo != null && (assetInfo.getAssetFrom() == 91||assetInfo.getAssetFrom() == 93)) {
            invalidateShelterView();
        }

        invalidateRestTime();
    }

    @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) {
        if (shelterView.getParent() != null) {
            removeView(shelterView);
        }
    }
    boolean seriesComplete;
    public void isLastSeriesFinish(boolean seriesComplete){
        this.seriesComplete=seriesComplete;
    }
    @Override
    public void onCompletion(MediaPlayer mediaPlayer) {
        WLog.i(TAG,"onCompletion assetInfo ="+assetInfo+",loadingView.getParent()="+loadingView.getParent());
        if(assetInfo!=null&&assetInfo.getAssetType()==DemandProgram.SHOWTYPE_MOVIE){
            showVideoLoadingPic();
        }else if(assetInfo!=null&&assetInfo.getAssetType()==DemandProgram.SHOWTYPE_TV_SERIES){
            WLog.i(TAG, "onCompletion mDemandInfo.getCurPlayIndex()="+assetInfo.getCurPlayIndex());
            if(getHistoryIndex(assetInfo.getCurPlayIndex())==assetInfo.getTotal()-1&&seriesComplete){
                showVideoLoadingPic();
            }
        } else {
            if (loadingView.getParent() == null) {
                addView(loadingView);
            }
        }
    }

	/**
     * 显示视频窗口默认loading图
     * @return
     */
    public void showVideoLoadingPic(){
        if (loadingView.getParent() == null) {
            addView(loadingView);
        }
    }
    private int getHistoryIndex(int mHistory_episode){
        if(assetInfo.getDetailSeriesSet()==null){
            return -1;
        }
        ArrayList<Integer> seriesList=assetInfo.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 onError(MediaPlayer mediaPlayer, int i, int i1) {
        if (loadingView.getParent() == null) {
            addView(loadingView);
        }
    }

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

    }

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

    }

    @Override
    public void onAdStatusChanged(int status, int extra) {
        switch (status) {
            case IMediaListener.AD_START:
                if (loadingView.getParent() != null) {
                    removeView(loadingView);
                }
                break;
            case IMediaListener.AD_END:

                break;
        }
    }

    @Override
    public void onWasuError(int i, String s) {
        if (loadingView.getParent() == null) {
            addView(loadingView);
        }
    }

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

    }

}
