package gen2wave.rp70biodemo.fingersuprema;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.List;

import gen2wave.rp70biodemo.R;
import gen2wave.rp70biodemo.tools.SendCommToDatabaseFragment;

/**
 * Created by mastyle on 17. 6. 7.
 */
public class SpDatabaseFragment extends SpBaseFragment implements SendCommToDatabaseFragment {


    final String TAG = "SpDatabaseFragment";


    private ArrayList<String> mUsersname;;
    private ArrayAdapter itemsAdapter;
    private ListView listviewdata;

    Button updateBtn = null, refreshBtn = null, removeBtn = null, removeAllBtn = null;

    DbHelper dbhelper;
    SQLiteDatabase db;
    Cursor cursor;
    Context maincontext;
    String selected;
    int seletposition;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        maincontext=context;
        Log.d(TAG, "onAttach");

        ((FingerSupremaMainActivity)context).sendCommToDatabaseFragment = (SendCommToDatabaseFragment) this;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "onCreate");
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.database_fragment_main, container, false);
        getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

        mUsersname = new ArrayList<String>();

        dbhelper = new DbHelper(getActivity());
        db = dbhelper.getWritableDatabase();
        cursor = db.rawQuery("select * from tablename",null);

        while(cursor.moveToNext()){
            mUsersname.add(cursor.getString(0));
        }


        Log.d(TAG, "ArrayAdapter");
        itemsAdapter= new ArrayAdapter(getActivity(),android.R.layout.simple_list_item_1,mUsersname);
        Log.d(TAG, "listviewdata");
        listviewdata = (ListView)rootView.findViewById(R.id.database_listview);
        Log.d(TAG, "setAdapter");
        listviewdata.setAdapter(itemsAdapter);
        listviewdata.setOnItemClickListener(listViewItemlistener);

        updateBtn = (Button) rootView.findViewById(R.id.update_user_btn);
        updateBtn.setOnClickListener(buttonListener);
        refreshBtn = (Button) rootView.findViewById(R.id.refresh_btn);
        refreshBtn.setOnClickListener(buttonListener);
        removeBtn = (Button) rootView.findViewById(R.id.remove_user_btn);
        removeBtn.setOnClickListener(buttonListener);
        removeAllBtn = (Button) rootView.findViewById(R.id.remove_all_btn);
        removeAllBtn.setOnClickListener(buttonListener);
        return rootView;
    }

    ListView.OnItemClickListener listViewItemlistener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            final List<String> databaseItems = mUsersname;
            // Take action here.
            selected =  listviewdata.getItemAtPosition(position).toString();
            seletposition = position;

            if (databaseItems != null && selected != null) {


                for (int i = 0; i < listviewdata.getChildCount(); i++) {
                    View v = listviewdata.getChildAt(i);
                    if (v != null) {
                        v.setBackgroundColor(Color.TRANSPARENT);
                    }
                }
                view.setBackgroundColor(Color.CYAN);
            }

        }
    };

    @Override
    public void onResume() {
        super.onResume();
        Log.d(TAG, "onResume");
    }

    public int loadDatabaseItem() {
        int ret = 0;
        Log.d(TAG, "loadDatabaseItem");
        cursor = db.rawQuery("select * from tablename",null);

        mUsersname.clear();
        while(cursor.moveToNext()){
            mUsersname.add(cursor.getString(0));
        }
        itemsAdapter.notifyDataSetChanged();

        return ret;
    }



    Button.OnClickListener buttonListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {


            int id = v.getId();
            switch (id) {
                case R.id.refresh_btn:
                    Log.d(TAG, "refresh_btn");
                    loadDatabaseItem();
                    break;
                case R.id.update_user_btn:
                    Log.d(TAG, "update_user_btn");
                    if (seletposition != -1) {
                        //LayoutInflater factory = LayoutInflater.from(getContext());
                        LayoutInflater factory = LayoutInflater.from(getActivity());
                        final View textEntryView = factory.inflate(R.layout.user_information, null);
                        final EditText idUser = (EditText) textEntryView.findViewById(R.id.idnumberUI);

                        idUser.setEnabled(false);
                        idUser.setText(selected);

                        final AlertDialog alertDialog = new AlertDialog.Builder(getActivity()).create();
                        alertDialog.setTitle("User Update Dialog");
                        alertDialog.setMessage("Update User : ");
                        alertDialog.setCancelable(false);
                        alertDialog.setView(textEntryView);
                        alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        });
                        alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        });

                        alertDialog.show();
                    }
                    break;
                case R.id.remove_user_btn:
                    if (seletposition != -1) {
                        db.execSQL("delete from tablename where name = '" + selected + "';");
                        mUsersname.remove(seletposition);
                        itemsAdapter.notifyDataSetChanged();
                    }
                    Log.d(TAG, "remove_user_btn");
                    break;
                case R.id.remove_all_btn:
                    Log.d(TAG, "remove_all_btn");

                    break;
            }
        }
    };

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        Log.d(TAG, "onDestroyView");
        seletposition = -1;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy");
    }


    @Override
    public void refreshList() {
        Log.d(TAG, "refreshList in Database");

    }


}
