package com.dbs.dbsec.activity.fragment;

import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.dbs.dbsec.BuildConfig;
import com.dbs.dbsec.R;
import com.dbs.dbsec.activity.ConsentActivity;
import com.dbs.dbsec.activity.adapter.CategoryAdapter;
import com.dbs.dbsec.activity.adapter.ConsentListAdapter;
import com.dbs.dbsec.httpTask.CallBack;
import com.dbs.dbsec.httpTask.ParseJsonData;
import com.dbs.dbsec.model.CategoryVO;
import com.dbs.dbsec.model.ConsentFormListVO;
import com.dbs.dbsec.util.Common;
import com.dbs.dbsec.util.ConsentConfig;

import java.util.ArrayList;
import java.util.HashMap;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

public class SearchFragment extends Fragment {

  private static final String TAG = "SearchFragment";

  private AppCompatActivity mActivity;
  private Context mContext;
  private ConsentActivity instance;

  private CategoryAdapter categoryAdapter;
  private ConsentListAdapter consentListAdapter;

  private LinearLayoutManager linearLayoutManager;
  private LinearLayout searchClickLayout;
  private RecyclerView searchRecyclerView;

  private Spinner  searchDeptSpinner;
  private TextView tvHospitalName;
  private EditText etKeyWord;
  private TextView tvEmptySearchConsent;

  private String categoryId = "";


  public SearchFragment() {
  }

  public SearchFragment(AppCompatActivity mActivity, Context mContext) {
    this.mActivity = mActivity;
    this.mContext  = mContext;
    this.instance = (ConsentActivity) mContext;
  }

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

  }

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

    View view = (View) inflater.inflate(R.layout.activity_search_fragment, container, false);

    searchDeptSpinner    = (Spinner) view.findViewById(R.id.searchDeptSpinner);
    tvHospitalName       = (TextView) view.findViewById(R.id.tvHospitalName);
    etKeyWord            = (EditText) view.findViewById(R.id.etKeyWord);
    searchClickLayout    = (LinearLayout) view.findViewById(R.id.searchClickLayout);
    searchRecyclerView   = (RecyclerView) view.findViewById(R.id.searchRecyclerView);
    tvEmptySearchConsent = (TextView) view.findViewById(R.id.tvEmptySearchConsent);

    getCategoryList(BuildConfig.INST_CD);

    setEvent();

    return view;
  }

  private void setEvent() {
    searchClickLayout.setOnClickListener(onClickListener);
    etKeyWord.setOnEditorActionListener(onEditorActionListener);
  }

  private View.OnClickListener onClickListener = new View.OnClickListener() {
    @Override
    public void onClick(View v) {
      if (v == searchClickLayout) {
        getConsentBySearch(categoryId);
      }
    }
  };

  public EditText.OnEditorActionListener onEditorActionListener = new EditText.OnEditorActionListener() {
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
      if (actionId == EditorInfo.IME_ACTION_DONE || actionId == EditorInfo.IME_ACTION_NEXT) {
        if (v == etKeyWord) {
          getConsentBySearch(categoryId);
        }
      }
      return false;
    }
  };

  /** Spinner List API **/
  /**
   * 동의서 검색 조건에 필요한 카테고리 데이터를 가져온다
   * @author jksong
   * @since 2020-01-28 오후 5:05
   **/
  private void getCategoryList(final String instCd) {
    CallBack callBack = new CallBack() {

      @Override
      public void result(final String result) {

        mActivity.runOnUiThread(new Runnable() {
          @Override
          public void run() {
            ArrayList<HashMap<String, String>> arrayList = Common.parseJSON(mContext, result);
            String code = arrayList.get(0).get("code");
            Log.e(TAG, "getCategoryList -- > " + result);

            if (!code.equals("00")) {
              stop();
            } else {
              instance.dismissProgress();
              ArrayList<CategoryVO> categoryArr = ParseJsonData.getInstance(mContext).getCategoryList(arrayList);
              setSpinnerAdapter(categoryArr);
            }
          }
        });

      }

      @Override
      public void stop() {
        instance.dismissProgress();
      }

      @Override
      public void error() {

      }
    };

    if (instCd.equals("031")) {
      tvHospitalName.setText(getText(R.string.knuh));
    } else {
      tvHospitalName.setText(getText(R.string.chilgok));
    }

    HashMap<String, String> mData = new HashMap<String, String>();
    mData.put("instCd", instCd);
    if (Common.checkNetwork(mContext) == true) {
      instance.showProgress();
      Common.callHttp(mContext, ConsentConfig.GET_CATEGORY_LIST, mData, callBack);
    } else {
      Common.networkErrorAlert(mActivity);
    }
  }

  private void setSpinnerAdapter(final ArrayList arrayList) {
    mActivity.runOnUiThread(new Runnable() {
      @Override
      public void run() {
        categoryAdapter = new CategoryAdapter(mActivity, arrayList);
        searchDeptSpinner.setAdapter(categoryAdapter);
        searchDeptSpinner.setOnItemSelectedListener(onItemSelectedListener);
      }
    });
  }

  private Spinner.OnItemSelectedListener onItemSelectedListener = new Spinner.OnItemSelectedListener() {
    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
      CategoryVO categoryVO = (CategoryVO) parent.getAdapter().getItem(position);
      categoryId = categoryVO.getCategoryId();
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }
  };

  /**
   * 동의서 찾기 리스트
   * @author jksong
   * @since 2020-01-28 오후 5:03
   **/
  private void getConsentBySearch(String categoryId) {
    CallBack callBack = new CallBack() {
      @Override
      public void result(final String result) {
        Log.e(TAG, "getConsentBySearch -- > " + result);
        mActivity.runOnUiThread(new Runnable() {
          @Override
          public void run() {
            instance.dismissProgress();
            ArrayList<HashMap<String, String>> arrayList = Common.parseJSON(mContext, result);
            String code = arrayList.get(0).get("code");

            if (!code.equals("00")) {
              stop();
            } else {
              tvEmptySearchConsent.setVisibility(View.GONE);
              ArrayList<ConsentFormListVO> consentArr = ParseJsonData.getInstance(mContext).getConsentFormList(arrayList);
              setConsentAdapter(consentArr);
            }
          }
        });

      }
      @Override
      public void stop() {
        tvEmptySearchConsent.setVisibility(View.VISIBLE);

        if (consentListAdapter != null) {
          consentListAdapter.arrayList.clear();
          consentListAdapter.notifyDataSetChanged();
        }
      }
      @Override
      public void error() {

      }
    };

    if (categoryId.equals("1") && etKeyWord.getText().toString().trim().equals("")) {
//      categoryNotSelected
      instance.showSingButtonDialog(mContext.getString(R.string.categoryNotSelected));
    } else {
      instance.showProgress();
      HashMap<String, String> mData = new HashMap<String, String>();
      mData.put("instCd", BuildConfig.INST_CD);
      mData.put("keyWord", etKeyWord.getText().toString().trim());
      mData.put("categoryId", categoryId);

      if (Common.checkNetwork(mContext) == true) {
        Common.callHttp(mContext, ConsentConfig.GET_CONSENT_BY_SEARCH, mData, callBack);
      } else {
        instance.dismissProgress();
        Common.networkErrorAlert(mActivity);
      }
    }
  }

  private void setConsentAdapter(final ArrayList<ConsentFormListVO> arrayList) {
    if (consentListAdapter == null) {
      linearLayoutManager = new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false);
      searchRecyclerView.setLayoutManager(linearLayoutManager);
      consentListAdapter = new ConsentListAdapter(mActivity, mContext, arrayList, ConsentConfig.GET_CONSENT_BY_SEARCH);
      searchRecyclerView.setAdapter(consentListAdapter);
    } else {
      consentListAdapter.arrayList = arrayList;
      consentListAdapter.notifyDataSetChanged();
    }
  }

}
