/**
 * @Title: FavoriteActivity.java
 * @Package com.wasu.tvplayersdk.ui
 * @author duhuanbiao
 * @date 2014年10月20日 下午5:36:40
 * @Description:
 */
package com.wasu.cs.ui;


import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.wasu.cs.adapter.ChildFavRecyclerAdapter;
import com.wasu.cs.adapter.OnItemDeleteListener;
import com.wasu.cs.adapter.OnItemFocusChangeListener;
import com.wasu.cs.module.ChildFavModule;
import com.wasu.cs.widget.BlockLinearLayout;
import com.wasu.cs.widget.DialogChildrenFav;
import com.wasu.cs.widget.ListScrollView;
import com.wasu.cs.widget.TimeLineView;
import com.wasu.module.log.WLog;
import com.wasu.statistics.WasuStatistics;

import java.util.ArrayList;
import java.util.List;
import java.util.TimeZone;

import basic.BuilderTypeManager.BuildType;
import basic.db.model.DBProgramChildFavorite;
import cn.com.wasu.main.R;

/**
 * 收藏和历史公用页面
 */
public class ActivityChildrenFav extends ActivityBase implements
        View.OnFocusChangeListener, View.OnClickListener, OnItemFocusChangeListener, OnItemDeleteListener {

    private String TAG = "ActivityChildrenFav";
    public static final String LIGHT = "#ffffff";
    public static final String DARK = "#7fffffff";

    private final String PAGEVIEWTYPE = "ChildrenFavorite";
    private final String PAGENAME = "少儿收藏页";
    private final String CATNAME = "少儿收藏页";

    //收藏记录
    private List<RowData> mRowDatas;
    private List<TextView> titles;
    private List<RecyclerView> recyclerViews;


    //no content
    private TextView mNoContentTextview;

    //内容区

    //删除
    private ImageView mDelAllImageView;
    private TextView mDelAllTextView;
    //历史收藏内容
    private ListScrollView mFavContentView;

    private ListScrollView.Adapter mAdapter;

    private LinearLayout mTimeLineLayout;
    private BlockLinearLayout focusSearchLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        WLog.i(TAG,"onCreate()");
    }


    @Override
    protected void doCreate(Bundle savedInstanceState) {
       // addTestData();
        setContentView(R.layout.activity_child_favorite);
        initView();
    }

    @Override
    protected void setDefaultBg(Drawable drawable) {
        setBg(R.drawable.children_common_bg);
    }


    private int mItemHeight;

    /**
     * 初始化控件，设置监听
     */
    private void initView() {

        mItemHeight = (int) getResources().getDimension(R.dimen.d_303dp);
        mNoContentTextview = (TextView) findViewById(R.id.tx_no_content);

        mDelAllImageView = (ImageView) findViewById(R.id.del_all_iv);
        mDelAllTextView = (TextView) findViewById(R.id.del_all_tv);
        mFavContentView = (ListScrollView) findViewById(R.id.fav_content_view);
        mFavContentView.setmItemHeight(mItemHeight);
        mDelAllTextView.setOnClickListener(this);
        mDelAllTextView.setOnFocusChangeListener(this);

        mTimeLineLayout = (LinearLayout) findViewById(R.id.timeline_layout);
        focusSearchLayout = (BlockLinearLayout) findViewById(R.id.layoutBody);
        focusSearchLayout.setOnFocusSearchListener(focusSearchListener);
    }

    /**
     * 焦点分发拦截控制
     */
    private final BlockLinearLayout.OnFocusSearchListener focusSearchListener = new BlockLinearLayout.OnFocusSearchListener() {
        @Override
        public View onFocusSearch(View focused, int direction) {
            if (direction == View.FOCUS_LEFT || direction == View.FOCUS_RIGHT) {
                return focused;
            }
            return null;
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        mCurIndex = -1;

        if (mFavContentView == null) {//无网络时控件未初始化，会crash
            return;
        }
        initFavoriteData();
        WasuStatistics.getInstance().pageViewStart(PAGEVIEWTYPE);

    }

    @Override
    protected void onPause() {
        super.onPause();
        WasuStatistics.getInstance().pageViewEnd(PAGEVIEWTYPE,CATNAME,PAGENAME);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    //删除一行时刷新数据
    public void refresh() {
        mCurIndex = -1;
        mRowDatas.clear();
        initFavoriteData();
    }


    private void addOneFavorite(int programId, String programPic, String name) {
        DBProgramChildFavorite favorite = new DBProgramChildFavorite();
        favorite.domain = BuildType.HTTP_DOMAIN;
        favorite.programId = programId;// 1234291;
        favorite.programPic = programPic;// "http://bs3-epg.wasu.tv/xml240/_CMS_NEWS_IMG_/www224/2014-12/23/1419319884357_911586.jpg";
        favorite.programName = name;// "猩球崛起2";
        favorite.showType = 1;
        favorite.savefavoritetime = System.currentTimeMillis();
        ChildFavModule.getInstance().saveFavorite(favorite);
    }

    private void addOneFavoriteWeek(int programId, String programPic, String name) {
        DBProgramChildFavorite favorite = new DBProgramChildFavorite();
        favorite.domain = BuildType.HTTP_DOMAIN;
        favorite.programId = programId;// 1234291;
        favorite.programPic = programPic;// "http://bs3-epg.wasu.tv/xml240/_CMS_NEWS_IMG_/www224/2014-12/23/1419319884357_911586.jpg";
        favorite.programName = name;// "猩球崛起2";
        favorite.showType = 1;
        favorite.savefavoritetime = System.currentTimeMillis() - 24 * 60 * 60 * 1000;
        ChildFavModule.getInstance().saveFavorite(favorite);
    }

    private void addOneFavoriteMore(int programId, String programPic, String name) {
        DBProgramChildFavorite favorite = new DBProgramChildFavorite();
        favorite.domain = BuildType.HTTP_DOMAIN;
        favorite.programId = programId;// 1234291;
        favorite.programPic = programPic;// "http://bs3-epg.wasu.tv/xml240/_CMS_NEWS_IMG_/www224/2014-12/23/1419319884357_911586.jpg";
        favorite.programName = name;// "猩球崛起2";
        favorite.showType = 1;
        favorite.savefavoritetime = System.currentTimeMillis() - 8 * 24 * 60 * 60 * 1000;
        ChildFavModule.getInstance().saveFavorite(favorite);
    }

    private void addTestData() {
        int programId = 1234391;
        String programPic = "https://s-cms.wasu.tv/pic/wsimage/2016/11/28/101/101/201611280820498537202ba0e.jpg";
        String name = "猩球崛起2";
        for (int i = 0; i < 10; i++) {
            addOneFavorite(programId++, programPic, name);
            addOneFavoriteWeek(programId + 10, programPic, name);
            addOneFavoriteMore(programId + 30, programPic, name);

        }
    }


    private void alertDialog() {
        DialogChildrenFav.Builder builder = new DialogChildrenFav.Builder(this);
        builder.setMessage("确定删除所有收藏记录？");
        builder.setPositiveButton(new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                mRowDatas.clear();
                mFavContentView.removeAllViews();
                ChildFavModule.getInstance().deleteAllFavorite();
                showNoContent();
            }
        });

        builder.setNegativeButton(new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                mDelAllTextView.requestFocus();
            }
        });

        builder.create().show();
    }

    private void showNoContent() {
        mNoContentTextview.setVisibility(View.VISIBLE);
        mDelAllImageView.setVisibility(View.GONE);
        mDelAllTextView.setVisibility(View.GONE);
        mFavContentView.setVisibility(View.GONE);
    }


    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        switch (v.getId()) {
            case R.id.del_all_tv:
                if (hasFocus) {
                    setLineByIndex(-1);
                    setTitleByIndex(-1, -1);
                    mDelAllTextView.setText("按OK键清空");
                    mDelAllImageView.setSelected(true);
                    viewGroupReset(viewGroup);
                } else {
                    mDelAllTextView.setText("全部删除");
                    mDelAllImageView.setSelected(false);
                }
                break;
            default:
                break;
        }
    }

    /**
     * @param index 第几个recyclerview
     * @param pos   recyclerview中的位置
     */
    public void setRecyclerViewItemFocus(int index, final int pos) {
        if (index < recyclerViews.size()) {
            final RecyclerView recyclerView = recyclerViews.get(index);
            recyclerView.postDelayed(new Runnable() {
                @Override
                public void run() {
                    View view = recyclerView.getLayoutManager().findViewByPosition(pos);
                    if (view != null) {
                        view.requestFocus();
                    }
                }
            }, 200);
        }
    }

    @Override
    public void onItemDelete(int pos, int index) {
        setRecyclerViewItemFocus(index, pos);
    }

    @Override
    public void onAllItemDelete() {
        refresh();
    }


    /**
     * 初始化收藏数据，并设置Adapter
     **/
    private void initFavoriteData() {
        new FetchDataAsyncTask().execute();
    }


    class FetchDataAsyncTask extends AsyncTask<Integer, Integer, String> {
        @Override
        protected void onPreExecute() {
            showLoading();
        }

        @Override
        protected String doInBackground(Integer... params) {
            List<DBProgramChildFavorite> mFavoriteList = ChildFavModule.getInstance().readFavorite();
            mRowDatas = new ArrayList<>();
            if (mFavoriteList != null && mFavoriteList.size() > 0) {
                List<DBProgramChildFavorite> dayList = new ArrayList<>();
                List<DBProgramChildFavorite> weekList = new ArrayList<>();
                List<DBProgramChildFavorite> moreList = new ArrayList<>();
                for (DBProgramChildFavorite dBProgramChildFavorite : mFavoriteList) {
                    long curTime = System.currentTimeMillis();
                    long hisTime = dBProgramChildFavorite.savefavoritetime;
                    if (isToday(curTime, hisTime)) {
                        dayList.add(dBProgramChildFavorite);
                    } else if (isThisWeek(curTime, hisTime)) {
                        weekList.add(dBProgramChildFavorite);
                    } else {
                        moreList.add(dBProgramChildFavorite);
                    }
                }
                if (dayList != null && dayList.size() > 0) {
                    mRowDatas.add(new RowData(dayList, "今天"));
                }
                if (weekList != null && weekList.size() > 0) {
                    mRowDatas.add(new RowData(weekList, "7天内"));
                }
                if (moreList != null && moreList.size() > 0) {
                    mRowDatas.add(new RowData(moreList, "更早"));
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            hideLoading();
            if (mRowDatas == null || mRowDatas.size() <= 0) {
                showNoContent();
            } else {
                titles = new ArrayList<>();
                recyclerViews = new ArrayList<>();
                mAdapter = new MyAdapter();
                mFavContentView.setAdapter(mAdapter);
                setRecyclerViewItemFocus(0, 0);
                mTimeLineLayout.removeAllViews();
                for (int i = 0; i < mRowDatas.size(); i++) {
                    TimeLineView timeLineView = new TimeLineView(ActivityChildrenFav.this);
                    if (i == 0) {
                        timeLineView.setIsFirst(true);
                    }
                    ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                            mItemHeight);
                    timeLineView.setLayoutParams(layoutParams);
                    mTimeLineLayout.addView(timeLineView);
                }
                //加线
                if (mRowDatas.size() == 1) {
                    TimeLineView line = new TimeLineView(ActivityChildrenFav.this);
                    line.setRadius(0);
                    ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                            mItemHeight);
                    line.setLayoutParams(layoutParams);
                    mTimeLineLayout.addView(line);
                    //为scollerview添加一个空view增加高度
                    View view = new View(ActivityChildrenFav.this);
                    view.setLayoutParams(layoutParams);
                    mFavContentView.addChildView(view);
                }
            }
        }

    }

    private boolean isToday(long curTime, long hisTime) {
        long zero = curTime / (1000 * 3600 * 24) * (1000 * 3600 * 24) - TimeZone.getDefault().getRawOffset();
        return (hisTime >= zero && hisTime < zero + 1000 * 60 * 60 * 24);
    }

    private boolean isThisWeek(long curTime, long hisTime) {
        long zero = curTime / (1000 * 3600 * 24) * (1000 * 3600 * 24) - TimeZone.getDefault().getRawOffset();
        return (hisTime < zero && hisTime > zero - 7 * 1000 * 3600 * 24);
    }


    public void setLineByIndex(int index) {
        if (index != mCurIndex) {
            TimeLineView view = (TimeLineView) mTimeLineLayout.getChildAt(index);
            if (view != null) {
                view.setPaintCircleColor(LIGHT);
            }
            TimeLineView curView = (TimeLineView) mTimeLineLayout.getChildAt(mCurIndex);
            if (curView != null) {
                curView.setPaintCircleColor(DARK);
            }
        }
    }


    public void setTitleByIndex(int index, int pos) {
        if (index >= 0 && index < titles.size()) {
            TextView view = titles.get(index);
            view.setTextColor(Color.parseColor(LIGHT));
            view.setText(mRowDatas.get(index).getTitle() + " " + (pos + 1) + "|" + mRowDatas.get(index).getFavList().size());
        }
        if (index != mCurIndex) {
            if (mCurIndex >= 0 && mCurIndex < titles.size()) {
                TextView view = titles.get(mCurIndex);
                view.setTextColor(Color.parseColor(DARK));
                view.setText(mRowDatas.get(mCurIndex).getTitle());
            }
            mCurIndex = index;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.del_all_tv:
                alertDialog();
                break;
            default:
                break;
        }
    }

    ViewGroup viewGroup = null;

    void viewGroupReset(ViewGroup viewGroup) {
        if (viewGroup != null) {
            if (viewGroup.getChildAt(1) != null)
                viewGroup.getChildAt(1).setVisibility(View.GONE);
            viewGroup.setScaleX(1F);
            viewGroup.setScaleY(1F);
        }
    }

    int mCurIndex = -1;
    int mCurPos = -1;

    @Override
    public void onItemFocusChange(ViewGroup vG, int pos, boolean hasfocus, int index) {
        if (hasfocus) {
            if (vG != viewGroup) {
                viewGroupReset(viewGroup);
            }
            mCurPos = pos;
            viewGroup = vG;
            setLineByIndex(index);
            setTitleByIndex(index, pos);
        }
    }

    @Override
    public void onFirstItemFocusLeft() {

    }


    class RowData {
        List<DBProgramChildFavorite> mFavList;
        String mTitle;

        public RowData(List<DBProgramChildFavorite> favList, String title) {
            mFavList = favList;
            mTitle = title;
        }

        public String getTitle() {
            return mTitle;
        }

        public List<DBProgramChildFavorite> getFavList() {
            return mFavList;
        }
    }

    class MyAdapter extends ListScrollView.Adapter {


        @Override
        public View getView(ListScrollView parent, int pos) {
            View view = LayoutInflater.from(ActivityChildrenFav.this).inflate(R.layout.item_children_fav_row_layout, null);
            ChildFavRecyclerAdapter adapter = new ChildFavRecyclerAdapter(ActivityChildrenFav.this, mRowDatas.get(pos).getFavList(), pos);
            adapter.setOnItemFocusChangeListener(ActivityChildrenFav.this);
            adapter.setOnItemClickListener(ActivityChildrenFav.this);
            RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.recyclerview);
            LinearLayoutManager layoutManager = new LinearLayoutManager(ActivityChildrenFav.this, LinearLayoutManager.HORIZONTAL, false);
            recyclerView.setLayoutManager(layoutManager);
            recyclerView.setAdapter(adapter);
            TextView tv_title = (TextView) view.findViewById(R.id.tv_title);
            tv_title.setText(mRowDatas.get(pos).getTitle());
            recyclerViews.add(recyclerView);
            titles.add(tv_title);
            return view;
        }

        @Override
        public int getCount() {
            return mRowDatas.size();
        }
    }


}
