package com.dbs.consent.demo.fragment;

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

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.consent.demo.BuildConfig;
import com.dbs.consent.demo.R;
import com.dbs.consent.demo.activity.ConsentActivity;
import com.dbs.consent.demo.adapter.CategoryAdapter;
import com.dbs.consent.demo.adapter.ConsentListAdapter;
import com.dbs.consent.demo.customView.CustomAlertDialog;
import com.dbs.consent.demo.customView.LoadingProgress;
import com.dbs.consent.demo.httpTask.CallBack;
import com.dbs.consent.demo.httpTask.SoapParser;
import com.dbs.consent.demo.model.CategoryVO;
import com.dbs.consent.demo.model.ConsentFormListVO;
import com.dbs.consent.demo.util.ConsentConfig;
import com.dbs.consent.demo.util.Util;

import org.ksoap2.serialization.SoapObject;

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

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 etPatientId;
  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);
    etPatientId          = (EditText) view.findViewById(R.id.etPatientId);
    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);
    etPatientId.setOnEditorActionListener(onEditorActionListener);
  }

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

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

  /** Spinner List API **/
  /**
   * 동의서 검색 조건에 필요한 카테고리 데이터를 가져온다
   * @author jksong
   * @since 2020-01-28 오후 5:05
   **/
  private void getCategoryList(final String instCd) {
    instance.showProgress();
    CallBack callBack = new CallBack() {
      @Override
      public void result(SoapObject result) {
        if (result == null || result.toString().indexOf("null") > 0) {
          stop();
        } else {
          ArrayList<CategoryVO> categoryArray = SoapParser.getHospitalList(result);
          setSpinnerAdapter(categoryArray);
        }
      }

      @Override
      public void stop() {

      }

      @Override
      public void error() {

      }
    };

    if (instCd.equals(BuildConfig.INST_CD)) {
      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 (Util.checkNetwork(mContext) == true) {
      Util.callHttp(mContext, ConsentConfig.HOST_CONSENT, ConsentConfig.GET_CONSENT_CATEGORYY, mData, callBack);
    } else {
      instance.dismissProgress();
      Util.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 getConsentList(String categoryId) {
    CallBack callBack = new CallBack() {
      @Override
      public void result(final SoapObject result) {

        mActivity.runOnUiThread(new Runnable() {
          @Override
          public void run() {
            Log.e(TAG, "getConsentList result -- > " + result);
            instance.dismissProgress();
            if (result == null || result.toString().indexOf("null") > 0 || result.getPropertyCount() == 0) {
              tvEmptySearchConsent.setVisibility(View.VISIBLE);
            } else {
              tvEmptySearchConsent.setVisibility(View.GONE);
              ArrayList<ConsentFormListVO> arrayList = SoapParser.getConsentList(result);
              setConsentAdapter(arrayList);
            }
          }
        });

      }
      @Override
      public void stop() {
      }
      @Override
      public void error() {

      }
    };

    if ((categoryId.equals("EMA_031") || categoryId.equals("EMA_032")) && etPatientId.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", etPatientId.getText().toString().trim());
      mData.put("categoryId", categoryId);

      if (Util.checkNetwork(mContext) == true) {
        Util.callHttp(mContext, ConsentConfig.HOST_CONSENT, ConsentConfig.GET_CONSENT_SEARCH, mData, callBack);
      } else {
        instance.dismissProgress();
        Util.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_SEARCH);
      searchRecyclerView.setAdapter(consentListAdapter);
    } else {
      consentListAdapter.arrayList = arrayList;
      consentListAdapter.notifyDataSetChanged();
    }
  }

}