package com.example.lfrmobileapp.ui.dashboard;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

import com.example.lfrmobileapp.Communication;
import com.example.lfrmobileapp.DataTransferAsyncTask;
import com.example.lfrmobileapp.R;
import com.example.lfrmobileapp.databinding.FragmentAutomatikBinding;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;

import kotlin.collections.UArraySortingKt;

public class DashboardFragment extends Fragment {

    String ipKey = "ipkey";
    String portKey = "portkey";

    String ipAddress = "192.168.0.1";
    int port = 8000;

    Communication com = new Communication();
    private FragmentAutomatikBinding binding;

    //Keys for Shared Preferences
    String listKey = "listkey";

    DataTransferAsyncTask dataTransferAsyncTask;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        DashboardViewModel dashboardViewModel =
                new ViewModelProvider(this).get(DashboardViewModel.class);

        binding = FragmentAutomatikBinding.inflate(inflater, container, false);
        View root = binding.getRoot();

        final TextView textView = binding.textDashboard;
        dashboardViewModel.getText().observe(getViewLifecycleOwner(), textView::setText);

        //Shared Preferences
        SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPref.edit();

        //Get Arraylist from Shared Preferences String
        ArrayList<String> autoList = stringToArraylist(sharedPref.getString(listKey, ""));

        ipAddress = sharedPref.getString(ipKey, "");
        port = sharedPref.getInt(portKey, -1);

        dataTransferAsyncTask = new DataTransferAsyncTask(ipAddress, port);
        dataTransferAsyncTask.execute();

        binding.startAutomatic.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked){
                    dataTransferAsyncTask.writeTelegram(com.telegram(true, autoList));
                }else{
                    dataTransferAsyncTask.writeTelegram(com.telegram(false, autoList));
                }
            }
        });


        // on the below line we are initializing the adapter for our list view.
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(root.getContext(), android.R.layout.simple_list_item_1, autoList){
            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                View view =super.getView(position, convertView, parent);
                TextView textView=(TextView) view.findViewById(android.R.id.text1);
                //Set Color to black
                textView.setTextColor(Color.BLACK);
                return view;
            }

            @Override
            public void notifyDataSetChanged() {
                super.notifyDataSetChanged();
                //Save Arraylist in Shared Preferences as String
                editor.putString(listKey, listToString(autoList));
                editor.apply();
            }
        };



        // on below line we are setting adapter for our list view.
        binding.automaticList.setAdapter(adapter);

        // on below line we are adding click listener for our button.
        binding.addLeft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // on below line we are getting text from edit text
                String item = "Links";
                Boolean automaticOn = binding.startAutomatic.isChecked();
                // on below line we are checking if item is not empty
                if (!item.isEmpty() && !automaticOn) {
                    // on below line we are adding item to our list.
                    autoList.add(item);
                    // on below line we are notifying adapter
                    // that data in list is updated to
                    // update our list view.
                    adapter.notifyDataSetChanged();
                }
            }
        });

        // on below line we are adding click listener for our button.
        binding.addRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // on below line we are getting text from edit text
                String item = "Rechts";

                Boolean automaticOn = binding.startAutomatic.isChecked();
                // on below line we are checking if item is not empty
                if (!item.isEmpty() && !automaticOn) {
                    // on below line we are adding item to our list.
                    autoList.add(item);
                    // on below line we are notifying adapter
                    // that data in list is updated to
                    // update our list view.
                    adapter.notifyDataSetChanged();
                }
            }
        });

        //Deleting element in ListView
        binding.automaticList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Boolean automaticOn = binding.startAutomatic.isChecked();
                if(!automaticOn) {
                    autoList.remove(position);
                    adapter.notifyDataSetChanged();
                }
            }
        });
        return root;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        dataTransferAsyncTask.cancel(false);
        binding = null;
    }

    public String listToString(ArrayList<String> list){
        String result = "";
        if(!list.isEmpty()) {
            for (String s : list) {
                result += s + ";";
            }
        }
        return result;
    }

    public ArrayList<String> stringToArraylist(String str){
        ArrayList<String> list = null;
        String[] stringArray = str.split(";");
        list = new ArrayList<String>(Arrays.asList(stringArray));
        return list;
    }
}

