package com.creativeapps.schoolbusdriver.ui.activity.main.settings;

import android.Manifest;
import android.app.AlertDialog;
import android.app.TimePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.text.Html;
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.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;

import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;

import com.creativeapps.schoolbusdriver.R;
import com.creativeapps.schoolbusdriver.data.Util;
import com.creativeapps.schoolbusdriver.data.network.models.Driver;
import com.creativeapps.schoolbusdriver.data.network.models.Parent;
import com.creativeapps.schoolbusdriver.ui.activity.main.MainActivity;
import com.creativeapps.schoolbusdriver.ui.activity.main.MainActivityModel;
import com.creativeapps.schoolbusdriver.ui.activity.main.map.base.BaseMaps;

import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;


public class SettingsFragment extends Fragment implements
        View.OnClickListener, AdapterView.OnItemSelectedListener {
    private static final String TAG = "SettingsFragment";
    private MainActivityModel mViewModel;
    private Driver mDriver;
    Button btnTimePicker;
    TextView txtTime;
    private ArrayList<String>  items;
    private NavController mNavigation;

    public SettingsFragment() {
        // Required empty public constructor
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mViewModel = ((MainActivity) getActivity()).createViewModel();
        mNavigation = ((MainActivity) getActivity()).navController;
    }

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

        mDriver = Util.getSavedObjectFromPreference(getContext(),
                "mPreference", "Driver", com.creativeapps.schoolbusdriver.data.network.models.Driver.class);

        if(mDriver!=null) {
            mViewModel.getDriverServer(mDriver.getCountry_code(), mDriver.getTel_number(), mDriver.getSecretKey());
        }
        else
        {
            ((MainActivity) getActivity()).logout();
        }

        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_settings, container, false);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {

        View background_location_access_gui1 = view.findViewById(R.id.background_location_access_gui1);
        View background_location_access_gui2 = view.findViewById(R.id.background_location_access_gui2);
        TextView background_access_status = view.findViewById(R.id.background_access_status);
        boolean backgroundAccess = false;
        if ( ContextCompat.checkSelfPermission( this.getActivity(),
                Manifest.permission.ACCESS_BACKGROUND_LOCATION ) == PackageManager.PERMISSION_GRANTED ) {
            Log.d(TAG, "onViewCreated: Background access ok!!!");
            backgroundAccess = true;
        }
        if(Build.VERSION.SDK_INT > Build.VERSION_CODES.Q)
        {
            background_location_access_gui1.setVisibility(View.VISIBLE);
            background_location_access_gui2.setVisibility(View.VISIBLE);
            background_access_status.setText(backgroundAccess? getString(R.string.allowed) : getString(R.string.not_allowed));
            Button btn_background_access = view.findViewById(R.id.btn_background_access);
            btn_background_access.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                    {
                        builder.setPositiveButton("Go to settings", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                Uri uri = Uri.fromParts("package",
                                        SettingsFragment.this.getActivity().getPackageName(), null);
                                intent.setData(uri);
                                startActivity(intent);
                            }
                        });
                        builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                            }
                        });
                    }
                    String warnMessage = "";
                    warnMessage = "Manage the background location access by tapping <b>Go to settings</b> below. " +
                            "Please select <b>Allow all the time</b> if you want to <b>allow</b> the background " +
                            "location access or select <b>Allow only while using the app</b> if you want " +
                            "to <b>disable</b> it.";
                    ImageView image = new ImageView(SettingsFragment.this.getActivity());
                    image.setImageResource(R.drawable.location_permission);
                    builder.setView(image);
                    builder.setMessage(Html.fromHtml(warnMessage));
                    builder.show();


                }
            });
        }

        View setOrder = view.findViewById(R.id.ll_set_order);
        Integer MAP_TYPE = Util.getSavedObjectFromPreference(getContext(),
                "mPreference", "MAP_TYPE", Integer.class);
        if(MAP_TYPE == null || MAP_TYPE == 0)
        {
            //show for map type 0
            setOrder.setVisibility(View.VISIBLE);
        }
        else
        {
            //show for map type 1
            setOrder.setVisibility(View.GONE);
        }

        Button btnSetOrder = (Button) view.findViewById(R.id.btn_set_order);

        RadioGroup radgroup = (RadioGroup) view.findViewById(R.id.radioGroup);
        //get navigation mode from shared preferences
        String navigation_mode = Util.getNavigationMode(getContext());
        if(navigation_mode != null && navigation_mode.equals("manual"))
        {
            radgroup.check(R.id.radio_manual);
            btnSetOrder.setVisibility(View.VISIBLE);
        }
        else
        {
            radgroup.check(R.id.radio_automatic);
            btnSetOrder.setVisibility(View.INVISIBLE);
        }

        radgroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                RadioButton radbtn = (RadioButton) view.findViewById(checkedId);
                //make btnSetOrder visible if the user select manual
                if(radbtn.getId() == R.id.radio_manual)
                {
                    btnSetOrder.setVisibility(View.VISIBLE);
                    Util.setNavigationMode(getContext(), "manual");
                }
                else
                {
                    btnSetOrder.setVisibility(View.INVISIBLE);
                    Util.setNavigationMode(getContext(), "auto");
                }
            }
        });

        // open ParentsContactsFragment fragment when btnSetOrder is clicked
        btnSetOrder.setOnClickListener(this);

        btnTimePicker = (Button) view.findViewById(R.id.btn_time);
        txtTime = (TextView) view.findViewById(R.id.in_time);
        btnTimePicker.setOnClickListener(this);

        String afternoon_time = Util.getSavedObjectFromPreference(getContext(),
                "mPreference", "afternoon_time", String.class);
        if (afternoon_time != null) {
            txtTime.setText(afternoon_time);
        }

        //get the spinner from the xml.
        Spinner dropdown = view.findViewById(R.id.spinner_last_afternoon);
        //create a list of items for the spinner.
        items = new ArrayList();
        items.add("School");
        for (Parent parent : mDriver.getParents()) {
            if(parent.getAddress_latitude() != null && parent.getAddress_longitude() != null) {
                items.add(parent.getName() + ":" + parent.getTel_number());
            }
        }
        //create an adapter to describe how the items are displayed, adapters are used in several places in android.
        //There are multiple variations of this, but this is the basic variant.
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this.getContext(),
                android.R.layout.simple_spinner_dropdown_item, items);
        //set the spinners adapter to the previously created one.
        dropdown.setAdapter(adapter);
        dropdown.setOnItemSelectedListener(this);

        String last_afternoon_parent = Util.getSavedObjectFromPreference(getActivity().getApplicationContext(),
                "mPreference", "last_afternoon_parent", String.class);
        if(last_afternoon_parent != null)
        {
            int spinnerPosition = adapter.getPosition(last_afternoon_parent);
            dropdown.setSelection(spinnerPosition);
        }
    }
    void displayPicker() {
        //display the time picker
        final Calendar c = Calendar.getInstance();
        int mHour = c.get(Calendar.HOUR_OF_DAY);
        int mMinute = c.get(Calendar.MINUTE);

        // Launch Time Picker Dialog
        TimePickerDialog timePickerDialog = new TimePickerDialog(this.getContext(),
                new TimePickerDialog.OnTimeSetListener() {
                    @Override
                    public void onTimeSet(TimePicker timePicker, int hourOfDay,
                                          int minute) {
                        Calendar c = Calendar.getInstance();
                        c.set(Calendar.HOUR_OF_DAY, hourOfDay);
                        c.set(Calendar.MINUTE, minute);
                        c.set(Calendar.SECOND, 0);
                        c.set(Calendar.MILLISECOND, 0);
                        String afternoon_time = getTime(c.getTime());
                        txtTime.setText(afternoon_time);
                        //save the afternoon time
                        Util.saveObjectToSharedPreference(getContext(), "mPreference",
                                "afternoon_time", afternoon_time);
                    }
                }, mHour, mMinute, false);
        timePickerDialog.show();
    }

    private String getTime(Date time) {
        SimpleDateFormat format = new SimpleDateFormat("hh:mm a", Locale.ENGLISH);
        return format.format(time);
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.btn_time) {
            displayPicker();
        }
        else if(view.getId() == R.id.btn_set_order)
        {
            // navigate to ParentsContactsFragment
            mNavigation.navigate(R.id.action_settingsFragment_to_parentsContactsFragment);
//            ((MainActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }
    }

    @Override
    public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
        String last_afternoon_parent = (String) adapterView.getItemAtPosition(position);
        if(position != 0)
        {
            Util.saveObjectToSharedPreference(getContext(), "mPreference",
                    "last_afternoon_parent", last_afternoon_parent);
        }
        else
        {
            Util.saveObjectToSharedPreference(getContext(), "mPreference",
                    "last_afternoon_parent", "School");
        }
    }

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

    }
}
