using Android.App;
using Android.OS;
using Android.Support.V7.App;
using Android.Runtime;
using Android.Widget;
using System.Collections.Generic;
using Android.Content.PM;

namespace Kontakty
{
    [Activity(Label = "@string/app_name", Theme = "@style/AppTheme", MainLauncher = true)]
    public class MainActivity : AppCompatActivity
    {
        private ListView listView;

        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.activity_main);

            if (Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.M && this.CheckSelfPermission(Android.Manifest.Permission.ReadContacts) != Permission.Granted)
            {
                this.RequestPermissions(new string[] { Android.Manifest.Permission.ReadContacts }, PERMISSIONS_REQUEST_READ_CONTACTS);
                //After this point you wait for callback in onRequestPermissionsResult(int, String[], int[]) overriden method
            }
            else
            {
                // Android version is lesser than 6.0 or the permission is already granted.
                showContacts();
            }
        }

        private void showContacts()
        {
            //dane dla listy
            List<string> lista = Kontakt.ListaNazwWszystkichKontaktow(this.ContentResolver);
            if (lista == null)
            {
                TextView naglowek = FindViewById<TextView>(Resource.Id.naglowek);
                naglowek.Text = "Brak zdefiniowanych kontaktów";
            }
            ArrayAdapter<string> adapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleListItem1, lista);

            // kontrolka
            listView = FindViewById<ListView>(Resource.Id.listView);
            listView.Adapter = adapter;
        }

        private const int PERMISSIONS_REQUEST_READ_CONTACTS = 100;

        public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Permission[] grantResults)
        {
            base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
            if (requestCode == PERMISSIONS_REQUEST_READ_CONTACTS)
            {
                if (grantResults[0] == Permission.Granted)
                {
                    // Permission is granted                    
                    showContacts();
                }
                else
                {
                    Toast.MakeText(this, "Nie można wyświetlać kontaktów do momentu udzielenia zgody", ToastLength.Short).Show();
                }
            }
        }
    }
}