using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using AndroidX.AppCompat.App;
using Com.Android.Hdhe.Uhf.Reader;
using System;
using System.Collections.Generic;

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

        private UhfReader uhfReader;
        public static EditText editTextEpc;
        private Button buttonInventoryEpc;
        public static KeyReceiver receiver;


        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.activity_main);
            editTextEpc = (EditText)FindViewById(Resource.Id.edittext_epc);
            buttonInventoryEpc = (Button)FindViewById(Resource.Id.inventory_epc);
            buttonInventoryEpc.Click += Button_Click;
            //buttonWrite.Click += Button_Click_write;
            receiver = new KeyReceiver();
            IntentFilter filter = new IntentFilter();
            filter.AddAction("android.rfid.FUN_KEY");
            filter.AddAction("android.intent.action.FUN_KEY");
            RegisterReceiver(receiver, filter);

            Intent intent = new Intent("com.rfid.CLOSE_SCAN");
            SendBroadcast(intent);

            //init 
            uhfReader = UhfReader.Instance;
            if (uhfReader != null)
            {
                uhfReader.SetOutputPower(26);// 15  26
                //uhfReader.SetWorkArea(2); //default 2:FCC,3:Eu
            }
        }

        protected override void OnDestroy()
        {
            if (receiver!=null)
            {
                UnregisterReceiver(receiver);
            }
            //if (mUHFManager != null) mUHFManager.Close();
            if (uhfReader != null) uhfReader.Close();


            base.OnDestroy();
        }
        public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
        {
            Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);

            base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
        }

        private void Button_Click(object sender, EventArgs e)
        {


            if (uhfReader != null)
            {
                //inventory epc
                IList<Com.Android.Hdhe.Uhf.ReaderInterface.TagModel> Ilist = uhfReader.InventoryRealTime();
                if (Ilist != null && Ilist.Count > 0)
                {
                    editTextEpc.Text = Ilist[0].GetmEpcString();
                }
                // read 
                //byte[] readdata = uhfreader.readfrom6c(1,2,6,new byte[4]);//epc 
                ////byte[] readdata = uhfreader.readfrom6c(2, 0, 6, new byte[4]);//tid
                //if (readdata != null) {
                //    edittextepc.text = tohexstring(readdata);//09 not tag
                //}
                // write 
                //byte[] writedata = { 0xaa,0xbb,0xcc,0xdd, 0xaa, 0xbb, 0xcc, 0xdd, 0xaa, 0xbb, 0xcc, 0xdd };
                //Boolean writeFlag = uhfReader.WriteTo6C(new byte[4], 1, 2, 6, writedata);
                //if (writeFlag) editTextEpc.Text = "write success"; else editTextEpc.Text = "write fail";
            }

        }






        public static string ToHexStrFromByte(byte[] byteDatas)
        {
            string hexString = BitConverter.ToString(byteDatas).Replace("-", "");
            return hexString.ToString().Trim();
        }

        public static byte[] HexStringToByteArray(string s)
        {
            s = s.Replace(" ", "");
            byte[] buffer = new byte[s.Length / 2];
            for (int i = 0; i < s.Length; i += 2)
            {
                buffer[i / 2] = (byte)Convert.ToByte(s.Substring(i, 2), 16);
            }
            return buffer;
        }

        public static String  ByteArrayToHexString(byte[] buffer)
        {
            String reString = "";
            if (buffer != null)
            {
                for(int i = 0; i < buffer.Length; i++)
                {
                    reString += buffer[i].ToString("X2");
                }
            }
            return reString;
        }

        public class KeyReceiver : BroadcastReceiver
        {
            public override void OnReceive(Context context, Intent intent)
            {
                int keyCode = intent.GetIntExtra("keyCode", 0);

                switch (keyCode)
                {
                    case 131:
                    case 132:
                    case 133:
                    case 134:
                    case 135:
                    case 136:
                    case 137:
                        Boolean keydown = intent.GetBooleanExtra("keydown", false);
                        if (!keydown)
                        {
                            //Add an inventory method here, which triggers the inventory when the button is lifted, 
                            // and will not be triggered when the button is pressed
                            editTextEpc.Append(keyCode + ";");
                        }


                        break;
                }
                    // Work that should be done when the device boots.     
                }
            }
    }

}