package com.dbs.mplus.fatima.fragment;

import android.content.Context;
import android.os.Bundle;
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 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;

import com.dbs.mplus.fatima.R;
import com.dbs.mplus.fatima.activity.ConsentActivity;
import com.dbs.mplus.fatima.adapter.CategoryAdapter;
import com.dbs.mplus.fatima.adapter.ConsentListAdapter;
import com.dbs.mplus.fatima.httpTask.DataParser;
import com.dbs.mplus.fatima.httpTask.HttpCallBack;
import com.dbs.mplus.fatima.model.CategoryVO;
import com.dbs.mplus.fatima.model.ConsentSetListVO;
import com.dbs.mplus.fatima.util.ConsentConfig;
import com.dbs.mplus.fatima.util.Util;

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 ConsentListAdapter consentListAdapter;

  private LinearLayoutManager linearLayoutManager;
  private LinearLayout searchClickLayout;
  private RecyclerView searchRecyclerView;
  private Spinner searchMainSpinner;
  private Spinner searchSubSpinner;
  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);

    searchMainSpinner    = (Spinner) view.findViewById(R.id.searchMainSpinner);
    searchSubSpinner     = (Spinner) view.findViewById(R.id.searchSubSpinner);
//    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);

    getMainCategoryList();
    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 || actionId == EditorInfo.IME_ACTION_NEXT) {
        if (v == etPatientId) {
          getConsentList(categoryId);
        }
      }
      return false;
    }
  };

  /** Spinner List API **/
  /**
   * 동의서 검색 조건에 필요한 카테고리 데이터를 가져온다
   * @author jksong
   * @since 2020-01-28 오후 5:05
   **/
  private void getMainCategoryList() {
    instance.showProgress();
    HttpCallBack callBack = new HttpCallBack() {
      @Override
      public void result(String result) {
        if (result.equals("")) {
          stop();
        } else {
          ArrayList<CategoryVO> categoryArray = DataParser.getCategoryList(mContext, result);
          setMainSpinnerAdapter(categoryArray);
        }
      }

      @Override
      public void stop() {

      }

      @Override
      public void error() {

      }
    };

    HashMap<String, String> mData = new HashMap<String, String>();
    mData.put("categoryId", "1");

    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 getSubCategoryList(String categoryId) {
    HttpCallBack callBack = new HttpCallBack() {
      @Override
      public void result(String result) {
        if (result.equals("")) {
          stop();
        } else {
          ArrayList<CategoryVO> categoryArray = DataParser.getCategoryList(mContext, result);
          setSubSpinnerAdapter(categoryArray);
        }
      }

      @Override
      public void stop() {

      }

      @Override
      public void error() {

      }
    };

    HashMap<String, String> mData = new HashMap<String, String>();
    mData.put("categoryId", categoryId);
    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 setMainSpinnerAdapter(final ArrayList arrayList) {
    mActivity.runOnUiThread(new Runnable() {
      @Override
      public void run() {
        CategoryAdapter categoryAdapter = new CategoryAdapter(mActivity, arrayList);
        searchMainSpinner.setAdapter(categoryAdapter);
        searchMainSpinner.setOnItemSelectedListener(onItemMainSelectedListener);
      }
    });
  }

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

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

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

    }
  };

  private Spinner.OnItemSelectedListener onItemSubSelectedListener = 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) {
    HttpCallBack callBack = new HttpCallBack() {
      @Override
      public void result(final String result) {
        mActivity.runOnUiThread(new Runnable() {
          @Override
          public void run() {
            instance.dismissProgress();
            if (result.equals("")) {
              tvEmptySearchConsent.setVisibility(View.VISIBLE);
              if (consentListAdapter != null) {
                consentListAdapter.arrayList.clear();
                consentListAdapter.notifyDataSetChanged();
              }
            } else {
              tvEmptySearchConsent.setVisibility(View.GONE);
              ArrayList<ConsentSetListVO> arrayList = DataParser.getConsentSetList(mContext, result, ConsentConfig.GET_CONSENT_SEARCH);
              setConsentAdapter(arrayList);
            }
          }
        });

      }

      @Override
      public void stop() {

      }

      @Override
      public void error() {

      }
    };

    HashMap<String, String> mData = new HashMap<String, String>();
    mData.put("categoryId", categoryId);
    mData.put("keyWord", etPatientId.getText().toString().trim());
    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<ConsentSetListVO> 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();
    }
  }

}