package com.usai.apex.KPI;

import android.animation.Animator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.usai.apex.R;
import com.usai.apex.mainframe.KPIFragment;

import java.util.ArrayList;
import java.util.Random;

public class KPICell extends RelativeLayout implements KPIListView.KPIListViewTouchListener,View.OnTouchListener {

    public KPICell(Context context) {
        super(context);
//        init();
    }

    public KPICell(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
//        init();
    }

    public KPICell(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
//        init();
    }


    private KPICell mCell;
    private ArrayList<PieChartView.ChartItem> mChartItems;
    private PieChartView mChartView;
    private ImageButton mPreBtn,mNextBtn;
    private TextView mShipTV,mContainerTV,mTeuTV,mSelectionTV;
    private KPIListView mItemListView;
    private ValueAnimator mAnimation;

    public void init() {

        mCell = this;

        mDetector = new GestureDetector(getContext(), new GestureListener());

        mShipTV = findViewById(R.id.shipmentTV);
        mContainerTV = findViewById(R.id.containerTV);
        mTeuTV = findViewById(R.id.teuTV);
        mSelectionTV = findViewById(R.id.selectionTV);

        mShipTV.setText(null);
        mContainerTV.setText(null);
        mTeuTV.setText(null);
        mSelectionTV.setText(null);

        mItemListView = findViewById(R.id.item_list);
        mAdapter = new KPIItemAdapter(getContext(),R.layout.kpi_item_cell);
        mItemListView.setAdapter(mAdapter);
        mItemListView.setListener(this);

        mChartView = findViewById(R.id.chart_view);

        if (mAnimation == null) {
            mAnimation = ValueAnimator.ofFloat(0f, 100f);

            mAnimation.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator updatedAnimation) {
                    // You can use the animated value in a property that uses the
                    // same type as the animation. In this case, you can use the
                    // float value in the translationX property.
                    float animatedValue = (float)updatedAnimation.getAnimatedValue();

                    mChartView.progress = animatedValue / 100.0f;
                    mChartView.postInvalidate();
                }
            });

            mAnimation.addListener(new Animator.AnimatorListener() {
                @Override
                public void onAnimationStart(Animator animation) {

                }

                @Override
                public void onAnimationEnd(Animator animation) {

                }

                @Override
                public void onAnimationCancel(Animator animation) {

                }

                @Override
                public void onAnimationRepeat(Animator animation) {

                }
            });

            mAnimation.setDuration(100);
        }


        mChartView.minTitleAngle = 20;
        mChartView.setPieChartItemClickListener(new PieChartView.PieChartItemClickListener() {
            @Override
            public void pieChartItemClicked(PieChartView pieChartView, PieChartView.ChartItem item) {

                if (mListener != null) {
                    mListener.KPIPieChartClickedItem(mCell,item);
                }
                mAnimation.end();

                mAnimation.start();

            }

            @Override
            public void pieChartCenterClicked(PieChartView pieChartView) {

                if (mListener != null) {
                    mListener.KPIPieChartClickedTitle(mCell);
                }
            }

            @Override
            public void pieChartDidBeginTouch() {
                if (mListener != null) {
                    mListener.KPIPieChartDidBeginClicked();
                }
            }

            @Override
            public void pieChartDidEndTouch() {
                if (mListener != null) {
                    mListener.KPIPieChartDidEndClicked();
                }
            }
        });

//        mPreBtn = findViewById(R.id.preBtn);
//        mPreBtn.setOnClickListener(new OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if (mListener != null) {
//                    mListener.KPIPreviousButtonClicked(mCell);
//                }
//            }
//        });
//
//        mNextBtn = findViewById(R.id.nextBtn);
//        mNextBtn.setOnClickListener(new OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if (mListener != null) {
//                    mListener.KPINextButtonClicked(mCell);
//                }
//            }
//        });
    }

    private void resizePieChartView(int w) {

        int leftInterval = dp2px(getContext(),60);
        int rightInterval = dp2px(getContext(),60);

        final int pieW = (w - leftInterval - rightInterval);


        mChartView.post(new Runnable() {

            @Override
            public void run() {

                LayoutParams layout = (LayoutParams)mChartView.getLayoutParams();
                layout.width = (int)pieW;
                layout.height = (int)pieW;
                mChartView.setLayoutParams(layout);
                mChartView.requestLayout();
            }
        });
    }

    public void setMonthShipment(String shipment, int color) {
        mShipTV.setText("Shipment:" + shipment);
        mShipTV.setTextColor(color);
    }

    public void setMonthContainer(String container, int color) {
        mContainerTV.setText("Container:" + container);
        mContainerTV.setTextColor(color);
    }

    public void setMonthTeu(String teu, int color) {
        mTeuTV.setText("TEU:" + teu);
        mTeuTV.setTextColor(color);
    }

    public void setNameAndCount(String name, int count) {
        if (mChartView != null) {
            mChartView.setNameAndCount(name,count);
        }
    }

    private KPIFragment.KPIModel mModel;
    public void setKPIModel(KPIFragment.KPIModel model) {
        mModel = model;
        if (model != null) {
            setChartItems(model.items);
            setNameAndCount(model.name,model.total);
        }
    }

    public void setSelection(String selection) {
        mSelectionTV.setText(selection);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {

        super.onSizeChanged(w, h, oldw, oldh);

    }

    private int mWidth = 0;
    private int mHeight = 0;

    public int getKPIWidth() {
        return mWidth;
    }

    public int getKPIHeight() {
        return mHeight;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        int w = getMeasuredWidth();
        int h = getMeasuredHeight();

        if (w != mWidth) {
//            resizePieChartView(w);
        }

        mWidth = w;
        mHeight = h;
    }


    float mTotal = 0;
    private ArrayList<PieChartView.ChartItem> preparePieChartItems() {

        float total = 0;
        ArrayList<PieChartView.ChartItem> displayItems = new ArrayList<>();

        if (mChartItems != null) {
            total = 0;
            for (int i = 0; i < mChartItems.size(); i++) {
                PieChartView.ChartItem item = mChartItems.get(i);
                if (item.display) {
                    total += item.value;
                }
            }
        } else {
            total = 0;
        }


        for (int i = 0; i < mChartItems.size(); i++) {
            PieChartView.ChartItem item = mChartItems.get(i);
            if (item.display) {
                if (total > 0) {
                    item.setPercentage(item.value / total);
                } else {
                    item.setPercentage(0.f);
                }

                displayItems.add(item);
            }
        }

        mTotal = total;
        return displayItems;
    }

    private void refreshUI() {
        ArrayList<PieChartView.ChartItem> displayItems = preparePieChartItems();
        mChartView.setChartItems(displayItems);
        mAdapter.notifyDataSetChanged();
    }

    public void setChartItems(ArrayList<PieChartView.ChartItem> chartItems) {
        mChartItems = chartItems;
        Log.d("KPI Cell", "setChartItems: ");
        refreshUI();
    }

    public void randomColor() {
        String r,g,b;
        Random random = new Random();
        r = Integer.toHexString(random.nextInt(256)).toUpperCase();
        g = Integer.toHexString(random.nextInt(256)).toUpperCase();
        b = Integer.toHexString(random.nextInt(256)).toUpperCase();

        r = r.length()==1 ? "0" + r : r ;
        g = g.length()==1 ? "0" + g : g ;
        b = b.length()==1 ? "0" + b : b ;
        int color = Color.parseColor("#" + r + g + b);
        setBackgroundColor(color);
    }

    public static int dp2px(Context context, float dpValue) {
        float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    private KPIItemAdapter mAdapter;

//    @Override
//    public void onClick(View v) {
//        if (v instanceof KPIItemButton) {
//            KPIItemButton button = (KPIItemButton) v;
//            Integer tag = (Integer) button.getTag();
//            PieChartView.ChartItem item = mChartItems.get(tag);
//            item.display = !item.display;
//            refreshUI();
//        }
//    }

    @Override
    public void KPIListViewTouched(boolean t) {
        if (mListener != null) {
            mListener.KPIListTouched(t);
        }
    }

    private class KPIItemAdapter extends BaseAdapter {

        class ViewHolder {
            KPIItemButton button_0, button_1;
            ViewHolder(View root) {
                if (root != null) {
                    button_0 = root.findViewById(R.id.item_btn_0);
                    button_1 = root.findViewById(R.id.item_btn_1);
                    root.setTag(this);
                }
            }
        }

        int mLayoutId;
        public KPIItemAdapter(Context context,int layoutId) {
            mLayoutId = layoutId;
        }

        @NonNull
        @Override
        public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {

            ViewHolder holder;
            if (convertView == null) {
                convertView = LayoutInflater.from(getContext()).inflate(mLayoutId,null);
                holder = new ViewHolder(convertView);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.button_0.setOnClickListener(null);
            holder.button_1.setOnClickListener(null);
            holder.button_0.setOnTouchListener(null);
            holder.button_1.setOnTouchListener(null);

            holder.button_0.setTitle(null);
            holder.button_1.setTitle(null);
            holder.button_0.setDotColor(Color.parseColor("#00000000"));
            holder.button_1.setDotColor(Color.parseColor("#00000000"));

            int index = 2 * position;
            PieChartView.ChartItem item_0 = mChartItems.get(index);

            if (item_0.display) {
                holder.button_0.setTitle(String.format("%s(%.2f%%)",item_0.shortTitle,item_0.getPercentage() * 100));
                holder.button_0.setTitleColor(Color.BLACK);
                holder.button_0.setDotColor(item_0.color);
            } else {
                holder.button_0.setTitle(item_0.shortTitle);
                holder.button_0.setDotColor(Color.LTGRAY);
                holder.button_0.setTitleColor(Color.LTGRAY);
            }

            holder.button_0.setTag(index);
            holder.button_0.setOnTouchListener(mCell);

            if (index < mChartItems.size() - 1) {
                PieChartView.ChartItem item_1 = mChartItems.get(index + 1);
                if (item_1.display) {
                    holder.button_1.setTitle(String.format("%s(%.2f%%)",item_1.shortTitle,item_1.getPercentage() * 100));
                    holder.button_1.setDotColor(item_1.color);
                    holder.button_1.setTitleColor(Color.BLACK);
                } else {
                    holder.button_1.setTitle(item_1.shortTitle);
                    holder.button_1.setDotColor(Color.LTGRAY);
                    holder.button_1.setTitleColor(Color.LTGRAY);
                }

                holder.button_1.setTag(index + 1);
                holder.button_1.setOnTouchListener(mCell);
            }

            return convertView;
        }

        @Override
        public int getCount() {

            if (mChartItems == null) {
                return 0;
            }

            int row = mChartItems.size() / 2;
            int col = mChartItems.size() % 2;
            if (col != 0) {
                row++;
            }

            return row;
        }

        @Override
        public Object getItem(int position) {
            int index = 2 * position;
            PieChartView.ChartItem item_0 = mChartItems.get(index);
            return item_0;
        }

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

    private KPIListener mListener;
    public void setListener(KPIListener listener) {
        mListener = listener;
    }

    public KPIListener getListener() {
        return mListener;
    }

    public interface KPIListener {

        void KPIPieChartClickedItem(KPICell cell, PieChartView.ChartItem item);
        void KPIPieChartClickedTitle(KPICell cell);
//        void KPIPreviousButtonClicked(KPICell cell);
//        void KPINextButtonClicked(KPICell cell);

        void KPIPieChartDidBeginClicked();
        void KPIPieChartDidEndClicked();

        void KPIListTouched(boolean touch);

        void KPICellDidDoubleClickItem(KPICell cell, int index, KPIFragment.KPIModel model);

    }

    private KPIItemButton mClickBtn;
    private GestureDetector mDetector;

    @Override
    public boolean onTouch(View v, MotionEvent event) {

        if (v instanceof KPIItemButton) {
            mClickBtn = (KPIItemButton) v;
            mDetector.onTouchEvent(event);
        }

        return true;
    }

    private class GestureListener extends GestureDetector.SimpleOnGestureListener {

        @Override
        public boolean onDoubleTapEvent(MotionEvent e) {


            if (e.getAction() == MotionEvent.ACTION_UP) {
                Log.d("KPI Cell", "onDoubleTapEvent: ");
                if (mListener != null) {
                    mListener.KPICellDidDoubleClickItem(mCell,(Integer) mClickBtn.getTag(),mModel);
                }
            }

            return false;
        }

        @Override
        public boolean onSingleTapConfirmed(MotionEvent e) {

            Log.d("KPI Cell", "onSingleTapConfirmed: ");
            if (mClickBtn != null) {
                KPIItemButton button = mClickBtn;
                Integer tag = (Integer) button.getTag();
                PieChartView.ChartItem item = mChartItems.get(tag);
                item.display = !item.display;
                refreshUI();
            }

            return false;
        }
    }
}
