package com.yidianling.dynamic.common.view;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.yidianling.dynamic.R;
import com.yidianling.dynamic.model.TrendsListBean;
import com.yidianling.dynamic.trendsDetail.TrendsDetailActivity;

import java.util.List;

/**
 * 为home_loop定制的view
 */
public class LooperTextView extends FrameLayout {
    private static final int STATUS_IN = 0;
    private static final int STATUS_OUT = 1;
    private List<TrendsListBean.ExtData> tipList;
    private int curTipIndex = 0;
    private long lastTimeMillis;
    private static final int ANIM_DELAYED_MILLIONS = 4 * 1000;
    /**
     * 动画持续时长
     */
    private static final int ANIM_DURATION = 1000;
    private static final String DEFAULT_TEXT_COLOR = "#2F4F4F";
    private static final int DEFAULT_TEXT_SIZE = 16;
    private View view_out, view_in;
    private TextView content_before_in;
    private TextView content_before_out;

    private Animation anim_out, anim_in;

    private Handler handler = new Handler();

    private  Runnable repeatCode = new Runnable() {
        @Override
        public void run() {
            updateTipAndPlayAnimation();
            handler.postDelayed(repeatCode, ANIM_DELAYED_MILLIONS);
        }
    };

    public LooperTextView(Context context) {
        super(context);
        initTipFrame();
        initAnimation();
    }

    public LooperTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initTipFrame();
        initAnimation();
    }

    public LooperTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initTipFrame();
        initAnimation();
    }

    private void initTipFrame() {
        view_out = newTextView(STATUS_OUT);
        view_in = newTextView(STATUS_IN);
        addView(view_in);
        addView(view_out);
    }

    private View newTextView(int status) {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.dynamic_looper_item, null, false);
        if (status == STATUS_IN) {
            content_before_in = (TextView) view.findViewById(R.id.loop_content_before);
        } else if (status == STATUS_OUT) {
            content_before_out = (TextView) view.findViewById(R.id.loop_content_before);
        }
        return view;
    }

    /**
     * 将资源图片转换为Drawable对象
     *
     * @param ResId
     * @return
     */
    private Drawable loadDrawable(int ResId) {
        Drawable drawable = getResources().getDrawable(ResId);
        drawable.setBounds(0, 0, drawable.getMinimumWidth() - 10, drawable.getMinimumHeight() - 10);
        return drawable;
    }

    private void initAnimation() {
        anim_out = newAnimation(0, -1);
        anim_in = newAnimation(1, 0);
        anim_in.setAnimationListener(new Animation.AnimationListener() {

            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                updateViewVisibility();
            }
        });
    }



    private Animation newAnimation(float fromYValue, float toYValue) {
        Animation anim = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0,
                Animation.RELATIVE_TO_SELF, fromYValue, Animation.RELATIVE_TO_SELF, toYValue);
        anim.setDuration(ANIM_DURATION);
        anim.setInterpolator(new DecelerateInterpolator());
        return anim;
    }

    private void updateTipAndPlayAnimationWithCheck() {
        if (System.currentTimeMillis() - lastTimeMillis < 1000) {
            return;
        }
        lastTimeMillis = System.currentTimeMillis();
        updateTipAndPlayAnimation();
    }

    private void updateViewVisibility() {
        if (curTipIndex % 2 == 0) {
            view_out.setVisibility(INVISIBLE);
        } else {
            view_in.setVisibility(INVISIBLE);
        }
    }

    private void updateTipAndPlayAnimation() {
        view_in.setVisibility(VISIBLE);
        view_out.setVisibility(VISIBLE);
        if (curTipIndex % 2 == 0) {
            updateTip(STATUS_OUT);
            view_in.startAnimation(anim_out);
            view_out.startAnimation(anim_in);
            this.bringChildToFront(view_in);
        } else {
            updateTip(STATUS_IN);
            view_out.startAnimation(anim_out);
            view_in.startAnimation(anim_in);
            this.bringChildToFront(view_out);
        }
    }

    private void updateTip(int status) {
        final TrendsListBean.ExtData tip = getNextTip();
        if (tip != null) {
            if (status == STATUS_IN) {
                SpannableString spannableString=new SpannableString("置顶 "+tip.getTitle());
                spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#FAA05A")), 0, 2, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                content_before_in.setText(spannableString);

                view_in.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        try {
                            TrendsDetailActivity.start(getContext(),Integer.valueOf(tip.getId()),false,false,false,false,0);
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                    }
                });
            } else if (status == STATUS_OUT) {
                SpannableString spannableString=new SpannableString("置顶 "+tip.getTitle());
                spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#FAA05A")), 0, 2, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                content_before_out.setText(spannableString);
                view_out.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        try {
                            TrendsDetailActivity.start(getContext(),Integer.valueOf(tip.getId()),false,false,false,false,0);
                        }catch (Exception e){
                            e.printStackTrace();
                        }

                    }
                });
            }
        }
    }

    /**
     * 获取下一条消息
     *
     * @return
     */
    private TrendsListBean.ExtData getNextTip() {
        if (isListEmpty(tipList)) return null;
        return tipList.get(curTipIndex++ % tipList.size());
    }

    public static boolean isListEmpty(List list) {
        return list == null || list.isEmpty();
    }

    public void setTipList(List<TrendsListBean.ExtData> tipList) {
        handler.removeCallbacks(repeatCode);
        this.tipList = tipList;
        curTipIndex = 0;
        updateTip(STATUS_OUT);
        updateTipAndPlayAnimation();
        handler.postDelayed(repeatCode, ANIM_DELAYED_MILLIONS);
    }

}
