package kr.co.hanwha.hifive.screen.main.home;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
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.LinearLayout;
import android.widget.TextView;

import java.util.List;

import kr.co.hanwha.hifive.R;
import kr.co.hanwha.hifive.adapter.MainHomeRequestListAdapter;
import kr.co.hanwha.hifive.adapter.MainMyHomeTodoListAdapter;
import kr.co.hanwha.hifive.adapter.SettingMyhomeOkrListAdapter;
import kr.co.hanwha.hifive.base.BaseFragment;
import kr.co.hanwha.hifive.base.FirebaseAnalyticsInterface;
import kr.co.hanwha.hifive.data.model.CampaignData;
import kr.co.hanwha.hifive.data.model.ProfileData;
import kr.co.hanwha.hifive.data.model.ProjectInfoData;
import kr.co.hanwha.hifive.data.model.TaskData;
import kr.co.hanwha.hifive.data.source.MemberDataRepository;
import kr.co.hanwha.hifive.screen.main.home.contract.MainHomeContract;
import kr.co.hanwha.hifive.screen.main.home.contract.MainMyHomeContract;
import kr.co.hanwha.hifive.screen.main.setting.myhome.contract.MyHomeContract;
import kr.co.hanwha.hifive.util.HFActivityUtil;
import kr.co.hanwha.hifive.view.HFMyHomeHeaderView;
import kr.co.hanwha.hifive.view.HFMyHomeProfileUnitView;
import kr.co.hanwha.hifive.view.HFMyHomeTabUnderlineView;

/**
 * Created by aaron on 2018. 10. 16.
 */
public class MainMyHomeFragment extends BaseFragment implements MainMyHomeContract.View, FirebaseAnalyticsInterface {

    private ViewPager mViewPager;
    private View mViewOkr;
    private View mViewTodo;
    private View mViewRequest;
    private View mViewProfile;
    private RecyclerView mRecyclerViewTodo;
    private RecyclerView mRecyclerViewOkr;
    private RecyclerView mRecyclerViewRequest;
    private SwipeRefreshLayout mRefreshLayoutOkr;
    private SwipeRefreshLayout mRefreshLayoutTodo;
    private SwipeRefreshLayout mRefreshLayoutRequest;
    private SwipeRefreshLayout mRefreshLayoutProfile;
    private SettingMyhomeOkrListAdapter mAdpaterOkr;
    private MainMyHomeTodoListAdapter mAdapterTodo;
    private MainHomeRequestListAdapter mAdapterRequest;
    private HFMyHomeTabUnderlineView mMyHomeTabUnderlineView;
    private HFMyHomeHeaderView mMyHomeHeaderView;
    private LinearLayout mLinearLayoutContainer;
    private LinearLayout mLinearLayoutNameEmail;
    private TextView mTextViewName;
    private TextView mTextViewEmail;
    private TextView mTextViewCompany;
    private TextView mTextViewPosition;
    private TextView mTextViewCellphone;
    private TextView mTextViewOkrEmpty;

    private MainMyHomePresenter mPresenter;

    public static final int INDEX_OKR = 0;
    public static final int INDEX_TODO = 1;
    public static final int INDEX_REQUEST = 2;
    public static final int INDEX_PROFILE = 3;

    private int mTabIndex = 0;
    private int mMemberId = MemberDataRepository.getInstance().getMemberId();

    private ProfileData mProfileData;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {

        View parent = inflater.inflate(R.layout.fragment_main_my_home, container, false);

        initLayout(parent);

        initPresenter();

        mPresenter.initDataOkr(mMemberId, true);
        mPresenter.initDataProfile(mMemberId, true);

        if (mTabIndex >= 0 && mTabIndex <= 3)
            mViewPager.setCurrentItem(mTabIndex);

        return parent;
    }

    @Override
    public void onResume() {
        super.onResume();
        mPresenter.initDataTodo(mMemberId, true);
        mPresenter.initDataRequest(mMemberId, true);
    }

    private void initLayout(View parent) {
//        setToolbarBackgroundColor(R.color.hf_grey19);

//        String memberName = getIntent().getStringExtra(HFActivityUtil.INTENT_MEMBER_NAME);
//        String loginId = getIntent().getStringExtra(HFActivityUtil.INTENT_MEMBER_LOGIN_ID);

        mMyHomeHeaderView = (HFMyHomeHeaderView) parent.findViewById(R.id.myHomeHeaderView);
//        mMyHomeHeaderView.setMemberInfo(memberName, loginId);
        mMyHomeHeaderView.setOnMyHomeClickListener(onMyHomeClickListener);

        mViewOkr = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_setting_my_home_okr, null);
        mViewTodo = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_main_home_sub, null);
        mViewRequest = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_main_home_sub, null);
        mViewProfile = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_setting_my_home_profile, null);

        mMyHomeTabUnderlineView = (HFMyHomeTabUnderlineView) parent.findViewById(R.id.myHomeTabUnderlineView);
        mMyHomeTabUnderlineView.setOnMyHomeTabListener(new HFMyHomeTabUnderlineView.OnMyHomeTabListener() {
            @Override
            public void onTabSelected(int position) {
                mViewPager.setCurrentItem(position);
            }
        });

        mViewPager = (ViewPager) parent.findViewById(R.id.viewPager);
        MainMyHomeFragment.MyHomePagerAdapter pagerAdapter = new MainMyHomeFragment.MyHomePagerAdapter();
        mViewPager.setAdapter(pagerAdapter);
        mViewPager.addOnPageChangeListener(onPageChangeListener);
        mViewPager.setOffscreenPageLimit(4);

        // OKR
        mRefreshLayoutOkr = (SwipeRefreshLayout) mViewOkr.findViewById(R.id.swipeRefreshLayout);
        mRefreshLayoutOkr.setOnRefreshListener(onOkrRefreshListener);

        mAdpaterOkr = new SettingMyhomeOkrListAdapter(getActivity(), onMyHomeOkrListListener);
        mRecyclerViewOkr = (RecyclerView) mViewOkr.findViewById(R.id.recyclerView);
        mRecyclerViewOkr.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRecyclerViewOkr.setAdapter(mAdpaterOkr);

        mTextViewOkrEmpty = (TextView) mViewOkr.findViewById(R.id.empty_textView);

        // To-Do
        mRefreshLayoutTodo = (SwipeRefreshLayout) mViewTodo.findViewById(R.id.swipeRefreshLayout);
        mRefreshLayoutTodo.setOnRefreshListener(onTodoRefreshListener);

//        mAdapterTodo = new SettingMyHomeTodoListAdapter(getActivity(), onMyHomeTodoListListener);
        mAdapterTodo = new MainMyHomeTodoListAdapter(getActivity(), onMainHomeListListener);
        mAdapterTodo.setFromMain(true);
        mRecyclerViewTodo = (RecyclerView) mViewTodo.findViewById(R.id.recyclerView);
        mRecyclerViewTodo.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRecyclerViewTodo.setAdapter(mAdapterTodo);

        //Request
        mRefreshLayoutRequest = (SwipeRefreshLayout) mViewRequest.findViewById(R.id.swipeRefreshLayout);
        mRefreshLayoutRequest.setOnRefreshListener(onRequestRefreshListener);

        mAdapterRequest = new MainHomeRequestListAdapter(getActivity(), onMainHomeListListener);
        mAdapterRequest.setFromMain(true);
        mRecyclerViewRequest = (RecyclerView) mViewRequest.findViewById(R.id.recyclerView);
        mRecyclerViewRequest.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRecyclerViewRequest.setAdapter(mAdapterRequest);

        // Profile
        mRefreshLayoutProfile = (SwipeRefreshLayout) mViewProfile.findViewById(R.id.swipeRefreshLayout);
        mRefreshLayoutProfile.setOnRefreshListener(onProfileRefreshListener);
        mLinearLayoutContainer = (LinearLayout) mViewProfile.findViewById(R.id.container_linearLayout);
        mLinearLayoutNameEmail = (LinearLayout) mViewProfile.findViewById(R.id.name_email_linearLayout);
        mTextViewName = (TextView) mViewProfile.findViewById(R.id.name_textView);
        mTextViewEmail = (TextView) mViewProfile.findViewById(R.id.email_textView);
        mTextViewCompany = (TextView) mViewProfile.findViewById(R.id.company_textView);
        mTextViewPosition = (TextView) mViewProfile.findViewById(R.id.position_textView);
        mTextViewCellphone = (TextView) mViewProfile.findViewById(R.id.cellPhone_textView);

        parent.findViewById(R.id.alarm_imageButton).setOnClickListener(onClickListener);
        parent.findViewById(R.id.search_imageButton).setOnClickListener(onClickListener);

    }

    private void initPresenter() {
        mPresenter = new MainMyHomePresenter(getActivity(), this, mAdapterTodo, mAdapterTodo, mAdpaterOkr, mAdpaterOkr, mAdapterRequest, mAdapterRequest);
    }

    /**************************************************
     * ViewPager.OnPageChangeListener
     **************************************************/
    ViewPager.OnPageChangeListener onPageChangeListener = new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            mMyHomeTabUnderlineView.onPageScrolled(position, positionOffset);
        }

        @Override
        public void onPageSelected(int position) {
            mMyHomeTabUnderlineView.setCurrentItem(position);
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    };

    /**************************************************
     * MyHomeContract.OnSettingMyHomeOkrListListener
     **************************************************/
    MyHomeContract.OnSettingMyHomeOkrListListener onMyHomeOkrListListener = new MyHomeContract.OnSettingMyHomeOkrListListener() {
        @Override
        public void onPlusClicked(@NonNull CampaignData campaignData) {
            HFActivityUtil.startAddTaskFromMyHomeActivity(getActivity(), mProfileData, campaignData);
        }

        @Override
        public void showEmptyView(boolean isShow) {
            mTextViewOkrEmpty.setVisibility(isShow ? View.VISIBLE : View.GONE);
        }
    };

    /**************************************************
     * MainHomeContract.OnMainHomeListListener
     **************************************************/
    MainHomeContract.OnMainHomeListListener onMainHomeListListener = new MainHomeContract.OnMainHomeListListener() {
        @Override
        public void onItemClicked(@NonNull TaskData data) {
            HFActivityUtil.startTaskDetailActivity(getActivity(), data);
        }

        @Override
        public void updateTodoTaskToTodayTask(@NonNull TaskData data, boolean isChecked) {
            mPresenter.updateTodoTaskToTodayTask(data, isChecked);
        }

        @Override
        public void onTaskAcceptClicked(@NonNull TaskData data) {
            mPresenter.doTaskAccept(data);
        }

        @Override
        public void onTaskRejectClicked(@NonNull TaskData data) {
            mPresenter.doTaskReject(data);
        }

        @Override
        public void onEvalAcceptClicked(@NonNull TaskData data) {
            mPresenter.doEvalAcceptClicked(data);
        }

        @Override
        public void onEvalRejectClicked(@NonNull TaskData data) {
            mPresenter.doEvalRejectClicked(data);
        }

        @Override
        public void onEvalRevaluationClicked(@NonNull TaskData data) {
            mPresenter.doEvalRevaluationClicked(data);
        }

        @Override
        public void onDeleteRequestClicked(@NonNull TaskData data) {
            mPresenter.doDeleteRequestClicked(data);
        }

        @Override
        public void onReRequestClicked(@NonNull TaskData data) {
            mPresenter.doReRequestClicked(data);
        }
    };

    /**************************************************
     * MyHomeContract.OnSettingMyHomeTodoListListener
     **************************************************/
    /*MyHomeContract.OnSettingMyHomeTodoListListener onMyHomeTodoListListener = new MyHomeContract.OnSettingMyHomeTodoListListener() {
        @Override
        public void onItemClicked(@NonNull TaskData data) {
            HFActivityUtil.startTaskDetailActivity(getActivity(), data);
        }
    };*/

    @Override
    public void refreshData() {

    }

    @Override
    public void stopRefreshOkr() {
        mRefreshLayoutOkr.setRefreshing(false);
    }

    @Override
    public void stopRefreshTodo() {
        mRefreshLayoutTodo.setRefreshing(false);
    }

    @Override
    public void stopRefreshRequest() {
        mRefreshLayoutRequest.setRefreshing(false);
    }

    @Override
    public void stopRefreshProfile() {
        mRefreshLayoutProfile.setRefreshing(false);
    }

    @Override
    public void setTabIndex(int index) {
        mTabIndex = index;
    }

    @Override
    public void setProfileUnit(List<ProjectInfoData> projects) {
        if (mLinearLayoutContainer.getChildCount() > 0)
            mLinearLayoutContainer.removeAllViews();

        for (final ProjectInfoData pid : projects) {
            HFMyHomeProfileUnitView view = new HFMyHomeProfileUnitView(getActivity());
            view.setProjectInfo(pid.getAchieve_rate(), pid.getProject_name());
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    HFActivityUtil.startDashboardProjectActivity(getActivity(), pid.getProject_id());
                }
            });
            mLinearLayoutContainer.addView(view);
        }
    }

    @Override
    public void setProfile(@NonNull ProfileData profileData) {
        mProfileData = profileData;
        mMyHomeHeaderView.setMemberInfo(profileData.getMember_name(), profileData.getLogin_id());
        mLinearLayoutNameEmail.setVisibility(View.VISIBLE);
        mTextViewName.setText(profileData.getMember_name());
        mTextViewEmail.setText(profileData.getLogin_id());
        mTextViewCompany.setText(profileData.getCompany());
        mTextViewPosition.setText(profileData.getRank_title());
        if (profileData.getPhone_mobile() != null && profileData.getPhone_mobile().isEmpty() == false)
            mTextViewCellphone.setText(profileData.getPhone_mobile());
        else
            mTextViewCellphone.setText(getString(R.string.setting_my_home_profile_empty_phone));
    }

    /**************************************************
     * View.OnClickListener
     **************************************************/
    View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.alarm_imageButton:
                    HFActivityUtil.startAlarmActivity(getActivity());
                    break;
                case R.id.search_imageButton:
                    HFActivityUtil.startSearchActivity(getActivity());
                    break;
            }

        }
    };

    HFMyHomeHeaderView.OnMyHomeClickListener onMyHomeClickListener = new HFMyHomeHeaderView.OnMyHomeClickListener() {
        @Override
        public void onPlusClick() {
            HFActivityUtil.startAddTaskFromMyHomeActivity(getActivity(), mProfileData, null);
        }
    };

    SwipeRefreshLayout.OnRefreshListener onOkrRefreshListener = new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            mPresenter.initDataOkr(mMemberId, false);
        }
    };

    SwipeRefreshLayout.OnRefreshListener onTodoRefreshListener = new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            mPresenter.initDataTodo(mMemberId, false);
        }
    };

    SwipeRefreshLayout.OnRefreshListener onRequestRefreshListener = new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            mPresenter.initDataRequest(mMemberId, false);
        }
    };

    SwipeRefreshLayout.OnRefreshListener onProfileRefreshListener = new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            mPresenter.initDataProfile(mMemberId, false);
        }
    };

    /**************************************************
     * PagerAdapter
     **************************************************/
    class MyHomePagerAdapter extends PagerAdapter {
        @Override
        public int getCount() {
            return 4;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            if (position == INDEX_OKR) {
                container.addView(mViewOkr);
                return mViewOkr;
            } else if (position == INDEX_TODO) {
                container.addView(mViewTodo);
                return mViewTodo;
            } else if (position == INDEX_REQUEST) {
                container.addView(mViewRequest);
                return mViewRequest;
            } else {
                container.addView(mViewProfile);
                return mViewProfile;
            }
        }

        @Override
        public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
            ((ViewPager) container).removeView((View) object);
        }
    }
}
