package com.android.chmo.ui.view;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.android.chmo.R;
import com.android.chmo.base.BaseFragment;
import com.android.chmo.http.HttpApi;
import com.android.chmo.http.RequestCallback;
import com.android.chmo.http.response.BannerRes;
import com.android.chmo.http.service.ActivitiesService;
import com.android.chmo.model.BannerInfo;
import com.android.chmo.ui.activity.activities.BannerInfoActivity;
import com.android.chmo.utils.PixelUtils;
import com.android.chmo.utils.XUtilsImage;
import com.google.gson.Gson;

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

import butterknife.BindView;

/**
 * 广告轮播界面
 */
public class BannerView extends RelativeLayout {
    private final int BANNER_TIME = 3000;


    private ViewPager pager;
    private PageIndexView indexView;

    private int curPage;

    private Handler mHandler;

    private BannerAdapter adapter;

    private FragmentManager fragmentManager;

    private List<BannerInfo> bannerList = new ArrayList<>();


    private Runnable bannerRunnable = new Runnable() {
        @Override
        public void run() {
            if (null == pager || bannerList.size() == 0) {
                return;
            }

            if (curPage == bannerList.size() - 1) {
                curPage = 0;
            } else {
                curPage++;
            }
            pager.setCurrentItem(curPage, true);
        }
    };

    public BannerView(Context context) {
        super(context);
        init();
    }
    public BannerView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        mHandler = new Handler();
        LayoutInflater.from(getContext()).inflate(R.layout.header_banner, this);
        pager = (ViewPager) findViewById(R.id.pager);
        pager.setOffscreenPageLimit(1);
        indexView = (PageIndexView) findViewById(R.id.index);
        indexView.setDefDrawable(R.mipmap.page_indicator);
        indexView.setSelectedIndexDrawable(R.mipmap.page_indicator_focused);

        pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                curPage = position;
                indexView.setCurIndex(position);
                mHandler.removeCallbacks(bannerRunnable);
                mHandler.postDelayed(bannerRunnable, BANNER_TIME);
            }

            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }
            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
        pager.setVisibility(View.GONE);
    }

    public void setSize(int width,int height) {
        ViewGroup.LayoutParams lp = getLayoutParams();
        if(null == lp) {
            lp = new ViewGroup.LayoutParams(width, height);
        }else {
            lp.width = width;
            lp.height = height;
        }
        setLayoutParams(lp);
    }



    public void setFragmentManager(FragmentManager fm) {
        fragmentManager = fm;
    }

    public void fillView() {
        int width = PixelUtils.getWindowWidth();
        int height = width / 3;
        AbsListView.LayoutParams lp = new AbsListView.LayoutParams(width, height);
        setLayoutParams(lp);
        pager.setVisibility(View.VISIBLE);
        adapter = new BannerAdapter(fragmentManager);
        pager.setAdapter(adapter);

        if (bannerList.size() > 1) {
            indexView.setCount(bannerList.size());
            indexView.setCurIndex(0);
            indexView.setVisibility(View.VISIBLE);
        } else {
            indexView.setVisibility(View.GONE);
        }
    }


    public void startLoop() {
        mHandler.removeCallbacks(bannerRunnable);
        mHandler.postDelayed(bannerRunnable, BANNER_TIME);
    }

    public void stopLoop() {
        mHandler.removeCallbacks(bannerRunnable);
    }


    public class BannerAdapter extends FragmentPagerAdapter {

        public BannerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            BannerPage fragment = (BannerPage) Fragment.instantiate(getContext(), BannerPage.class.getName());
            Bundle args = new Bundle();
            args.putSerializable("position",position);
            args.putSerializable("banner",bannerList.get(position));
            fragment.setArguments(args);
            return fragment;
        }

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


    public static class BannerPage extends BaseFragment {
        @BindView(R.id.ad_image)
        ImageView imageView;

        @Override
        public int getLayoutRes() {
            return R.layout.banner_image;
        }

        @Override
        public void initView() {
            Bundle args = getArguments();
            if (null != args) {
                final BannerInfo banner = (BannerInfo)args.getSerializable("banner");

                XUtilsImage.display(imageView, HttpApi.getImgUrl(banner.banner), R.mipmap.def_img2);

                imageView.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(getActivity(), BannerInfoActivity.class);
                        intent.putExtra("banner", banner);
                        openPage(intent);
                    }
                });
            }
        }
    }

    public void loadBanner() {
        ActivitiesService.getBanner(new RequestCallback() {
            @Override
            public void onSuccess(String result) {
                BannerRes res = new Gson().fromJson(result,BannerRes.class);
                if(res.msg.equals("success")) {
                    bannerList = res.data;
                   fillView();
                }
            }

            @Override
            public void onFailure(String error) {
            }
        });
    }

}
