package com.gensee.multi_instance.demo.player.holder;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.gensee.callback.IMedalPraiseCallback;
import com.gensee.multi_instance.R;
import com.gensee.praise.PraiseInfo;
import com.gensee.praise.PraiseUserInfo;
import com.gensee.routine.UserInfo;
import com.gensee.service.IMedalPraise;
import com.gensee.service.MedalPraise;
import com.gensee.utils.GenseeLog;

import java.util.concurrent.atomic.AtomicInteger;

public class MedalPraiseHolder implements IMedalPraiseCallback {
    private static final String TAG = "MedalPraiseHolder";

    private MedalPraise medalPraise;
    private Activity activity;
    private Handler mHandler;
    private UserInfo teacher;
    private TextView tvPraiseCount,btnPraise,btnMyMedal;
    private AtomicInteger selfPraiseRemain = new AtomicInteger(0);
    private AtomicInteger selfMedalTotal = new AtomicInteger(0);
    private long selfId;
    private int rankSize = 10;

    public String getSelfPraiseRemain() {
        return selfPraiseRemain.get()+"";
    }

    public String getSelfMedalTotal() {
        return selfMedalTotal.get() + "";
    }

    public void setBtnMyMedal(TextView btnMyMedal) {
        this.btnMyMedal = btnMyMedal;
    }

    public void setPraiseCount(TextView tvPraiseCount) {
        this.tvPraiseCount = tvPraiseCount;
    }

    public void setPraiseBtn(TextView btnPraise) {
        this.btnPraise = btnPraise;
    }

    public MedalPraiseHolder(Activity activity, Handler handler) {
        medalPraise = new MedalPraise(this);
        this.activity = activity;
        this.mHandler = handler;
    }

    /**
     * 发送点赞或勋章响应，一般更新发送者的剩余量，只有发送者才会回调
     * @param result 响应结果
     * @param type   类型：点赞和勋章
     * @param praiseUserInfo 发送者的点赞或勋章信息
     */
    @Override
    public void onPraiseInfo(int result,String type,PraiseUserInfo praiseUserInfo) {
        GenseeLog.i(TAG, "onPraiseInfo() called with: result = [" + result + "], type = [" + type + "], praiseUserInfo = [" + praiseUserInfo + "]");
        if (type == IMedalPraise.TYPE_FAOUR) {
            selfPraiseRemain.set(praiseUserInfo.getRemain());
            updateMyPraiseRemain(praiseUserInfo);
        } else if (type == IMedalPraise.TYPE_MEDAL) {
            selfMedalTotal.set(praiseUserInfo.getRecv());
            updateMyMedalCount(praiseUserInfo);
        }
    }

    @Override
    public void onPraiseTotal(int result,String praiseType,int total) {
        GenseeLog.i(TAG, "onPraiseTotal() called with: result = [" + result + "], praiseType = [" + praiseType + "], total = [" + total + "]");
        if (IMedalPraise.TYPE_FAOUR.equals(praiseType)) {
            updatePraiseCount(total);
        }
    }

    /**
     * 获取勋章排行榜响应
     * @param result 响应结果码
     * @param type 类型：勋章或点赞
     * @param praiseInfos 排行列表
     */
    @Override
    public void onPraiseRecvList(int result,String type,PraiseInfo[] praiseInfos) {
        GenseeLog.i(TAG, "onPraiseRecvList() called with: result = [" + result + "], praiseType = [" + type + "], praiseInfos = [" + praiseInfos + "]");
        if (result == 0) {
            activity.runOnUiThread(()->{
                if(IMedalPraise.TYPE_MEDAL.equals(type)){
                    new AlertDialog.Builder(activity).setAdapter(new RankingAdapter(praiseInfos),null).setTitle("勋章排行top"+rankSize).setNegativeButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    }).create().show();
                }
            });
        }
    }

    /**
     * 学生给老师点赞，所有人会响应该函数，receiverUserInfo 代表老师的点赞信息，可以更新老师收到的点赞数
     * 老师给学生发勋章，所有人会响应该函数，receiverUserInfo 代表该学生的勋章信息，可以更新该学生收到的勋章数目
     * @param type 勋章或点赞
     * @param senderUserInfo，发送者用户勋章或点赞信息
     * @param time 发送时间 单位：秒
     * @param receiverUserInfo 接收者勋章或点赞信息，praiseUserInfo.getUserId()接收者用户id
     * @param isBatch  是否是一批，一批的话，变化数量大于1
     */
    @Override
    public void onPraiseNotify(String type, boolean isBatch,int time,PraiseUserInfo senderUserInfo,PraiseUserInfo receiverUserInfo,String comment) {
        GenseeLog.i(TAG, "onPraiseNotify() called with: type = [" + type + "], time = [" + time + "], senderUserInfo = [" + senderUserInfo + "], receiverUserInfo = [" + receiverUserInfo + "], comment = [" + comment + "]");
        if (IMedalPraise.TYPE_FAOUR.equals(type)) {
            updatePraiseCount(receiverUserInfo.getRecv());
        } else if (IMedalPraise.TYPE_MEDAL.equals(type)) {
            if (selfId == receiverUserInfo.getUserId()) {
                updateMyMedalCount(receiverUserInfo);
            }
        }
    }


    @Override
    public void onSendPraiseInBatch(int i, String s, PraiseUserInfo praiseUserInfo) {

    }

    private void updateMyMedalCount(PraiseUserInfo recv) {
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                btnMyMedal.setText(activity.getString(R.string.my_medal)+recv.getRecv());
            }
        });
    }

    private void updateMyPraiseRemain(PraiseUserInfo senderUserInfo) {
        if (btnPraise != null) {
            activity.runOnUiThread(()-> btnPraise.setText(activity.getString(R.string.my_praise)+ senderUserInfo.getRemain()));
        }
    }

    public void getPraiseRecvList(String type) {
        medalPraise.getPraiseRecvList(type, rankSize);
    }

    public IMedalPraise getMedalPraise() {
        return medalPraise;
    }

    /**
     * 给老师点赞
     */
    public void clickPraise() {
        if (null != teacher) {
            medalPraise.sendPraise(IMedalPraise.TYPE_FAOUR, teacher.getUserId(), teacher.getName(), "");
        }
    }

    private void updatePraiseCount(int total) {
        activity.runOnUiThread(() -> {
            if (null != tvPraiseCount) {
                tvPraiseCount.setText(activity.getString(R.string.teacher_praise_total)+total);
            }
        });
    }

    public boolean isPraiseEnable() {
        return medalPraise.isPraiseEnable();
    }

    public boolean isMedalEnable() {
        return medalPraise.isMedalEnable();
    }

    public void setTeacherInfo(UserInfo teacher) {
        if (null != teacher) {
            this.teacher = teacher;
        }
    }

    public void setSelfId(long userId) {
        this.selfId = userId;
    }

    public void getPraiseTotal() {
        if (null != medalPraise) {
            medalPraise.getPraiseTotal(IMedalPraise.TYPE_FAOUR);
        }
    }

    class RankingAdapter extends BaseAdapter {
        private PraiseInfo[] infos;
        public RankingAdapter(PraiseInfo[] infos){
            this.infos = infos;
        }
        @Override
        public int getCount() {
            return infos == null?0:infos.length;
        }

        @Override
        public Object getItem(int position) {
            return infos[position];
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ItemHolder holder;
            if(convertView == null){
                convertView = LayoutInflater.from(activity).inflate(R.layout.rank_item_layout,null);
                holder = new ItemHolder(convertView);
                convertView.setTag(holder);
            }else{
                holder = (ItemHolder) convertView.getTag();
            }
            holder.update((PraiseInfo)getItem(position));
            return convertView;
        }

        class ItemHolder{
            private TextView rank;
            private TextView name;
            public ItemHolder(View rootView){
                rank = (TextView) rootView.findViewById(R.id.rank);
                name = (TextView) rootView.findViewById(R.id.name);
            }

            public void update(PraiseInfo info){
                if(info != null){
                    rank.setText("勋章数:"+info.getTotal());
                    name.setText(info.getUserName());
                }
            }
        }
    }
}
