package com.bokecc.livemodule.view.gift;

import android.content.Context;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.Gravity;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.bokecc.common.utils.Tools;
import com.bokecc.dwlivedemo.R;
import com.bokecc.gift.GiftListener;
import com.bokecc.gift.GiftManager;
import com.bokecc.gift.HistoryCallBack;
import com.bokecc.gift.SendGiftCallBack;
import com.bokecc.gift.impl.GiftManagerImpl;
import com.bokecc.gift.pojo.Gift;
import com.bokecc.gift.pojo.GiftInfo;
import com.bokecc.livemodule.live.DWLiveCoreHandler;
import com.bokecc.livemodule.view.gift.interfaces.GiftCallBack;
import com.bokecc.sdk.mobile.live.BaseCallback;
import com.bokecc.sdk.mobile.live.common.log.ELog;
import com.bokecc.sdk.mobile.live.pojo.InteractionConfigure;

import java.util.List;

public class GiftView extends LinearLayout implements GiftCallBack {
    private static final String TAG = "GiftView";

    public static final int LIST_TYPE = 1;
    public static final int BIG_IMAGE = 2;
    private BaseQueueHandler baseQueueHandler;
    private int line = 1;
    private boolean  isShowHead = false;
    private boolean  isShowNum = false;
    private float space = 15f;
    private int showType = LIST_TYPE;
    private GiftManager giftManager;
    private String token;
    private GiftListListener giftListListener;
    public GiftView(Context context) {
        this(context,null);
    }

    public GiftView( Context context,  AttributeSet attrs) {
        this(context, attrs,0);
    }

    public GiftView( Context context,  AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context,attrs);
    }

    private void initView(Context context, AttributeSet attrs) {
        setOrientation(VERTICAL);
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.GiftView);
        //获取对应的属性值 并初始化handler
        line = a.getInt(R.styleable.GiftView_line, 2);
        isShowHead = a.getBoolean(R.styleable.GiftView_showHead, false);
        isShowNum = a.getBoolean(R.styleable.GiftView_showNum, false);
        space = a.getDimensionPixelOffset(R.styleable.GiftView_space, 20);
        a.recycle();
    }

    /**
     * 设置显示最大条目数
     * */
    public void setMaxLine(int line){
        if (baseQueueHandler != null){
            ELog.e(TAG,"init 之后不支持设置 line");
        }
        this.line = line;
    }

    /**
     * 设置显示是否显示头像
     * */
    public void isShowHead(boolean isShowHead){
        if (baseQueueHandler != null){
            ELog.e(TAG,"init 之后不支持设置 isShowHead");
        }
        this.isShowHead = isShowHead;
    }

    /**
     * 是否显示礼物数
     * */
    public void isShowNum(boolean isShowNum){
        if (baseQueueHandler != null){
            ELog.e(TAG,"init 之后不支持设置 isShowNum");
        }
        this.isShowNum = isShowNum;
    }

    /**
     * 设置两个条目间距
     * */
    public void setListSpace(float space){
        if (baseQueueHandler != null){
            ELog.e(TAG,"init 之后不支持设置 setListSpace");
        }
        this.space = space;
    }

    public void setGiftListListener(GiftListListener giftListListener) {
        this.giftListListener = giftListListener;
    }

    /**
     * 设置展示类型
     * */
    public void init(final InteractionConfigure.GiftConfigure giftConfigure){
        if (line < 1){
            ELog.e(TAG,"最小条目数为1");
            return;
        }
        if (giftConfigure==null||giftConfigure.getGiftSwitch()==0){
            return;
        }
        if (giftConfigure.getSpecialEffects() == 1){
            showType = LIST_TYPE;
        }else if (giftConfigure.getSpecialEffects() == 2){
            showType = BIG_IMAGE;
        }
        if (showType == LIST_TYPE) {
            baseQueueHandler = new ListQueeuHandler(this);
            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) getLayoutParams();
            int height = Tools.getScreenHeight();
            params.topMargin = height / 3 + Tools.dipToPixel(70);
            GiftView.this.setLayoutParams(params);
            baseQueueHandler.initView(this, line, isShowHead, isShowNum, space, showType);
        } else if (showType == BIG_IMAGE){
            baseQueueHandler = new BigImageQueeuHandler(this);
            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) getLayoutParams();
            params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM|RelativeLayout.CENTER_HORIZONTAL);
            params.bottomMargin = Tools.dipToPixel(70);
            GiftView.this.setLayoutParams(params);
            setGravity(Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL);
            baseQueueHandler.initView(this, 1, isShowHead, isShowNum, space, showType);
        }
        DWLiveCoreHandler.getInstance().getInteractionToken(new BaseCallback<String>() {
            @Override
            public void onError(String error) {
                Toast.makeText(getContext(),"获取token失败，礼物功能不可用",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onSuccess(String msg) {
                giftManager = new GiftManagerImpl();
                GiftView.this.token = msg;
                giftManager.init(giftListener, DWLiveCoreHandler.getInstance().getViewer().getId(),DWLiveCoreHandler.getInstance().getRoomInfo().getEncryptId(),token,giftConfigure.getGiftSwitch());
//                giftManager.getGiftHistory(new HistoryCallBack() {
//                    @Override
//                    public void onSuccess(List<Gift> list) {
//
//                    }
//
//                    @Override
//                    public void onFail() {
//
//                    }
//                });
            }
        });


    }

    @Override
    public void onFinish() {
        setVisibility(GONE);
    }
    public void destroy(){
        if (baseQueueHandler!=null){
            baseQueueHandler.cancelAllGift();
        }
        if (giftManager!=null){
            giftManager.release();
        }
    }
    private GiftListener giftListener = new GiftListener() {

        @Override
        public void onInitFailure() {
            Toast.makeText(getContext(),"礼物初始化失败，礼物功能不可用",Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onInitSuccess(List<GiftInfo> giftInfos) {
            if (giftListListener!=null){
                giftListListener.onGiftList(giftInfos);
            }
        }

        @Override
        public void onGift(com.bokecc.gift.pojo.Gift gift) {

            if (gift == null|| TextUtils.isEmpty(gift.getFromUserId())||gift.getFromUserId().equals(DWLiveCoreHandler.getInstance().getViewer().getId())
            ||showType == 0){
                return;
            }
            if (getVisibility()==GONE||getVisibility()==INVISIBLE){
                setVisibility(VISIBLE);
            }
            if (baseQueueHandler!=null){
                baseQueueHandler.addGift(gift);
            }
        }

        @Override
        public void onConnectFailure() {
            Toast.makeText(getContext(),"连接断开，礼物功能不可用",Toast.LENGTH_SHORT).show();
        }
    };

    public void sendGIft(GiftInfo giftInfo, int num) {
        if (giftInfo==null||num<=0){
            return;
        }
        showSelf(giftInfo,num);
        if (giftManager!=null){
            giftManager.sendGift(giftInfo.id, num, new SendGiftCallBack() {
                @Override
                public void onSuccess() {
                    ELog.e(TAG,"send gift success");
                }

                @Override
                public void onFailure() {
                    Toast.makeText(getContext(),"礼物发送失败",Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

    private void showSelf(GiftInfo giftInfo, int num) {
        if (showType==0){
            return;
        }
        Gift gift = new Gift();
        gift.setGiftImg(giftInfo.giftThumbnail);
        gift.setGiftName(giftInfo.giftName);
        gift.setGiftNum(num);
        gift.setFromUserName(DWLiveCoreHandler.getInstance().getViewer().getName());
        gift.setFromUserAvatar("https://marketing-image.csslcloud.net/viewers/imgs/3.jpg");
        gift.setFromUserId(DWLiveCoreHandler.getInstance().getViewer().getId());
        if (getVisibility()==GONE||getVisibility()==INVISIBLE){
            setVisibility(VISIBLE);
        }
        ELog.e("GiftView","#####自己礼物  "+gift.getFromUserId());
        if (baseQueueHandler!=null){
            baseQueueHandler.addGift(gift);
        }
    }

    public void getHistory(HistoryCallBack historyCallBack) {
        if (giftManager!=null){
            giftManager.getGiftHistory(historyCallBack);
        }
    }

    public interface GiftListListener{
        void onGiftList(List<GiftInfo> list);
    }

    public void setOnConfigurationChanged(Configuration newConfig){
        if (baseQueueHandler!=null){
            baseQueueHandler.setOnConfigurationChanged(newConfig);
            if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE){
                baseQueueHandler.cancelAllGift();
            }
        }

    }
}
