package com.wasu.cs.ui;

import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.PopupWindow;

import com.wasu.authsdk.AuthSDK;
import com.wasu.authsdk.IAuthInterface;
import com.wasu.cs.model.Model;
import com.wasu.cs.model.RecommendModel;
import com.wasu.cs.model.SearchConfigModel;
import com.wasu.cs.model.SearchModel;
import com.wasu.cs.protocol.RecommendProtocol;
import com.wasu.cs.protocol.SearchConfigProtocol;
import com.wasu.cs.protocol.SearchProtocol;
import com.wasu.cs.protocol.SearchProtocol.ProtocolCallbackBase;
import com.wasu.cs.ui.FragmentSearchRecommend.ISearchRecommend;
import com.wasu.cs.ui.FragmentSearchResult.ISearchResult;
import com.wasu.cs.widget.HeaderGridViewEx;
import com.wasu.cs.widget.PosterItemLayout;
import com.wasu.cs.widget.SearchInputLayout;
import com.wasu.cs.widget.SearchInputLayout.ISearchInputCallback;
import com.wasu.module.log.WLog;
import com.wasu.widgets.focuswidget.CustomFocusGridView;
import com.wasu.widgets.focuswidget.CustomGridView;
import com.wasu.statistics.WasuStatistics;

import basic.BuilderTypeManager.BuildType;
import cn.com.wasu.main.Common;
import cn.com.wasu.main.IntentConstant;
import cn.com.wasu.main.R;

public class ActivitySearch extends ActivityBase implements ISearchRecommend, ISearchResult {
    private final String TAG = "ActivitySearch";
    private final String PAGEVIEWTYPE = "ActivitySearch";
    private final String PAGENAME = "搜索页";
    private final String CATNAME = "搜索页";

    private View mRoot;
    private PopupWindow mQrCodePopupWindow;
    private FragmentSearchRecommend mRecommendFrag;
    private FragmentSearchNoResult mNoResultFrag;
    private FragmentSearchResult resultFrag;
    private RecommendModel mRecommendModel;
    private SearchInputLayout mSearchInput;
    private SearchModel mSearchModel;

    private String mSearchUrl;
    private String mSearchKeyword;

    /**
     * 外调没有传URL使用这个URL
     */
    private String tempUrl = "http://tang-ds.cs.wasu.tv/?s=2002&p=sntSearch&k=" + Common.URL_KEY +
            "&v=" + Common.URL_V +
            "&rcatId=256787";


    /**
     * delete keyword too fast, will lead to result fragment replace recommend fragment.
     * but we wan't recommend fragment show.
     */
    private boolean mIsSearchIng = false;

    @Override
    protected void doCreate(Bundle savedInstanceState) {
        WLog.i(TAG,"doCreate()");

        setContentView(R.layout.activity_search);

        getDataFromIntent(getIntent());

        setupViews();

        requestRecommendUrl();
    }

    @Override
    protected void onResume() {
        super.onResume();
        WasuStatistics.getInstance().pageViewStart(PAGEVIEWTYPE);
    }

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

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

    @Override
    public void onBackPressed() {
        if (!mSearchInput.hasFocus()) {
            mSearchInput.delBtnRequestFocus();
        } else {
            super.onBackPressed();
        }
    }

    private boolean getDataFromIntent(Intent intent) {
        mSearchUrl = intent.getStringExtra(IntentConstant.DATAURI.value());
        if (TextUtils.isEmpty(mSearchUrl)) {
            mSearchUrl = tempUrl;
            return false;
        }
        return true;
    }

    private void setupViews() {
        mRoot = findViewById(R.id.search_root_linLay);

        mSearchInput = (SearchInputLayout) findViewById(R.id.search_input_layout);
//		searchInput.addTextChangedListener(new TextWatcher() {
//			
//			@Override
//			public void onTextChanged(CharSequence s, int start, int before, int count) {
//			}
//			
//			@Override
//			public void beforeTextChanged(CharSequence s, int start, int count,
//					int after) {
//			}
//			
//			@Override
//			public void afterTextChanged(Editable s) {
//				if (isShowRecommend(s.toString())) {
//					showRecommendFrag();
//				} else {
//					requestSearchData(s.toString());
//				}
//			}
//		});
        mSearchInput.setCallback(new ISearchInputCallback() {

            @Override
            public void onSearch(String s) {
                s = s.trim();
                if (isShowRecommend(s)) {
                    mIsSearchIng = false;
                    showRecommendFrag();
                } else {
                    mIsSearchIng = true;
                    requestSearchData(s);
                }
            }
        });

        mSearchInput.getSearchGridView().setOnGridViewColumnEndListener(new CustomGridView.GridViewColumnEndListener() {
            @Override
            public void onColumnEnd() {
                if (null != mRecommendFrag && mRecommendFrag.isVisible()) {
                    mRecommendFrag.getHeaderGV().requestFocus();

                } else if (null != mNoResultFrag && mNoResultFrag.isVisible()) {
                    mNoResultFrag.getRecommendLayout().requestFocus();

                } else if (null != resultFrag && resultFrag.isVisible()) {
                    resultFrag.getResultFGV().requestFocus();
                }
            }
        });
       
        OnFocusChangeListener focusListener = new OnFocusChangeListener() {

            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    showQRCodePopupWindow();
                }
            }
        };
        OnClickListener clickListener = new OnClickListener() {

            @Override
            public void onClick(View v) {
                showQRCodePopupWindow();
            }
        };
        View qrCodeWrapper = findViewById(R.id.search_qr_code_wrapper_linLay);

        String tvid = AuthSDK.getInstance().getValue(IAuthInterface.KEY_TVID);
        //阿里市场版，屏蔽微信二维码
        if (!TextUtils.isEmpty(tvid) && tvid.subSequence(0, 9).equals("2710AC003")) {
            View qrCodeWeixinIV = qrCodeWrapper.findViewById(R.id.search_qr_code_weixin_iv);
            View qrCodeWeixinTV = qrCodeWrapper.findViewById(R.id.search_qr_code_weixin_tv);
            qrCodeWeixinIV.setVisibility(View.GONE);
            qrCodeWeixinTV.setVisibility(View.GONE);
        }

        qrCodeWrapper.setOnFocusChangeListener(focusListener);
        qrCodeWrapper.setOnClickListener(clickListener);
    }

    private boolean isShowRecommend(String keyword) {
        if (TextUtils.isEmpty(keyword)
                && ((null == mRecommendFrag) || !mRecommendFrag.isVisible())) {
            return true;
        }
        return false;
    }

    private void showRecommendFrag() {
        WLog.i(TAG, "showRecommendFrag");
        if (null == mRecommendFrag) {
            mRecommendFrag = new FragmentSearchRecommend();
            mRecommendFrag.setOnGridViewColumnBeginListener(new HeaderGridViewEx.GridViewColumnBeginListener() {
                @Override
                public void onColumnBegin() {
                    mSearchInput.getSearchGridView().requestFocus();
                }
            });
        }
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.search_frag_wrapper_fraLay, mRecommendFrag)
//								   .addToBackStack(null)
                .commitAllowingStateLoss();
    }

    private void showResultFrag() {
        resultFrag = new FragmentSearchResult();
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.search_frag_wrapper_fraLay, resultFrag)
//			.addToBackStack(null)
                .commitAllowingStateLoss();

            resultFrag.setOnGridViewColumnBeginListener(new CustomFocusGridView.GridViewColumnBeginListener() {
                @Override
                public void onColumnBegin() {
                    mSearchInput.getSearchGridView().requestFocus();
                }
            });
    }

    private void showNoResultFrag() {
//		if (null != mNoResultFrag || mNoResultFrag.isVisible()) {
//			return;
//		}
        mNoResultFrag = new FragmentSearchNoResult();
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.search_frag_wrapper_fraLay, mNoResultFrag)
//			.addToBackStack(null)
                .commitAllowingStateLoss();
        mNoResultFrag.setOnGridViewColumnBeginListener(new CustomFocusGridView.GridViewColumnBeginListener() {
            @Override
            public void onColumnBegin() {
                mSearchInput.getSearchGridView().requestFocus();
            }
        });
    }

    /**
     * show wasu qrcode
     */
    private void showQRCodePopupWindow() {
        hideQRCodePopupWindow();

        if (null == mQrCodePopupWindow) {
            mQrCodePopupWindow = new PopupWindow();
            View contentView = LayoutInflater.from(getBaseContext()).inflate(R.layout.layout_search_qr_code, null, false);
            View weixinQr = contentView.findViewById(R.id.search_qr_code_weixin_linLay);
            String tvid = AuthSDK.getInstance().getValue(IAuthInterface.KEY_TVID);
            //阿里市场版，屏蔽微信二维码
            if (!TextUtils.isEmpty(tvid) && tvid.subSequence(0, 9).equals("2710AC003")) {
                weixinQr.setVisibility(View.GONE);
            }


//			View root = contentView.findViewById(R.id.search_qr_code_root_linLay);
//			root.setOnKeyListener(new OnKeyListener() {
//				
//				@Override
//				public boolean onKey(View v, int keyCode, KeyEvent event) {
//					if (event.getAction() == KeyEvent.ACTION_DOWN) {
//						hideQRCodePopupWindow();
//					}
//					return false;
//				}
//			});

            mQrCodePopupWindow = new PopupWindow(contentView,
                    getResources().getDimensionPixelOffset(R.dimen.d_1280dp),
                    getResources().getDimensionPixelOffset(R.dimen.d_720dp));
            mQrCodePopupWindow.setAnimationStyle(R.style.SearchPopuWindowAnimStyle);
            mQrCodePopupWindow.setOutsideTouchable(false);
            mQrCodePopupWindow.setClippingEnabled(false);
            mQrCodePopupWindow.setFocusable(true);
            mQrCodePopupWindow.setBackgroundDrawable(new BitmapDrawable());
        }

        mQrCodePopupWindow.showAtLocation(mRoot, Gravity.CENTER, 0, 0);
        mQrCodePopupWindow.update();
    }

    private void hideQRCodePopupWindow() {
        if (null != mQrCodePopupWindow && mQrCodePopupWindow.isShowing()) {
            mQrCodePopupWindow.dismiss();
        }
    }

    private void requestRecommendUrl() {
        if (TextUtils.isEmpty(mSearchUrl)) {
            WLog.w(TAG, "requestRecommendUrl() mSearchUrl is empty");
            return;
        }

        Uri fetchUri = Uri.parse(mSearchUrl);
        fetchUri = fetchUri.buildUpon()
                .appendQueryParameter("config", String.valueOf(1))
                .build();

        SearchConfigProtocol protocol = new SearchConfigProtocol();
        protocol.fetch(fetchUri.toString(), new ProtocolCallbackBase() {

            @Override
            public void onProtocolCallback(boolean success, String msg, Model model) {
                if (success) {
                    requestRecommendData(((SearchConfigModel) (model)).getRecommendUrl());
                }
            }
        });
    }

    private void requestRecommendData(String url) {
        if (TextUtils.isEmpty(url)) {
            WLog.w(TAG, "requestRecommendData() url is empty");
            return;
        }
        WLog.i(TAG, "requestRecommendData() url =" + url);
        RecommendProtocol protocol = new RecommendProtocol();
        protocol.fetch(url,
                new ProtocolCallbackBase() {

                    @Override
                    public void onProtocolCallback(boolean success, String msg, Model model) {
                        mRecommendModel = (RecommendModel) model;
                        WLog.i(TAG, "success=" + success + ",mRecommendModel=" + mRecommendModel);
                        /*if (success) {
                            showRecommendFrag();
						}*/
                        if (!isFinishing()&&!mIsSearchIng) {
                            showRecommendFrag();
                        }
                    }
                });
    }

    private void requestSearchData(final String keyword) {
        mSearchKeyword = keyword;

        if (TextUtils.isEmpty(keyword)) {
            WLog.w(TAG, "requestSearchData() keyword is empty");
            return;
        }

        if (TextUtils.isEmpty(mSearchUrl)) {
            WLog.w(TAG, "requestSearchData() search url is empty");
            return;
        }

        showLoading();

        Uri fetchUri = Uri.parse(mSearchUrl);
        fetchUri = fetchUri.buildUpon()
                .appendQueryParameter("word", String.valueOf(keyword))
                .appendQueryParameter("page", String.valueOf(1))
                .appendQueryParameter("psize", String.valueOf(100))
                .build();
        WLog.i(TAG, "requestSearchData fetchUri=" + fetchUri.toString());
        SearchProtocol protocol = new SearchProtocol();

        if (isFinishing()&&!mIsSearchIng) {
            WLog.w(TAG, "requestSearchData() cancel call");
            return;
        }

        protocol.fetch(fetchUri.toString(),
                new ProtocolCallbackBase() {

                    @Override
                    public void onProtocolCallback(boolean success, String msg, Model model) {
                        hideLoading();

                        if (isFinishing()&&!mIsSearchIng) {
                            return;
                        }

                        mSearchModel = (SearchModel) model;

                        if (success) {
//							WasuStatistics.getInstance().search(keyword, mSearchModel.getALLItemIds());
                            showResultFrag();
                        } else {
                            showNoResultFrag();
                        }
                    }
                });
    }

    @Override
    public RecommendModel getRecommend() {
        return mRecommendModel;
    }

    @Override
    public SearchModel getSearchResult() {
        return mSearchModel;
    }

    @Override
    public int getNextLeftFocusViewId() {
        // ...
        return R.id.search_input_gv;
    }

    @Override
    public String getSearchKeyword() {
        return mSearchKeyword;
    }

}
