// This file has been autogenerated from a class added in the UI designer.

using System;
using AsReaderDock4;
using Foundation;
using UIKit;
using System.Runtime.InteropServices;

namespace AsReaderDock_VS
{
	public partial class ReadWriteController : UIViewController
	{
        AsReaderDockManager dockManager = AsReaderDockManager.sharedInstance();

        public ReadWriteController(IntPtr handle) : base(handle)
        {
        }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();
            olScrollVeiw.ScrollEnabled = true;
            olScrollVeiw.ContentSize = new CoreGraphics.CGSize(this.View.Frame.Width, this.View.Frame.Height + 600);
            NSNotificationCenter.DefaultCenter.AddObserver(new NSString("UIKeyboardWillShowNotification"), keyboardWillShow);
        }
        public override void ViewWillAppear(bool animated)
        {
            base.ViewWillAppear(animated);
            olAccessPassword.ShouldReturn = (olAccessPassword) =>
            {
                return ShouldReturn(olAccessPassword);
            };
            olStartAdress.ShouldReturn = (olStartAdress) =>
            {
                return ShouldReturn(olStartAdress);
            };
            olLength.ShouldReturn = (olLength) =>
            {
                return ShouldReturn(olLength);
            };
            olData.ShouldReturn = (olData) =>
            {
                return ShouldReturn(olData);
            };
            olTargetEpc.ShouldReturn = (olTargetEpc) =>
            {
                return ShouldReturn(olTargetEpc);
            };
            olData.Delegate = new ReadWriteDelegate();
            ModelSettings model = ModelSettings.sharedInstance();
            NSDictionary dic = model.m_arReadTagData.GetItem<NSDictionary>((nuint)model.m_nSelectTagNum);
            NSData data = (NSData)dic.ObjectForKey(new NSString(GlobalDefine.df_CELL_TAG_RAW));
            olTargetEpc.Text = PhyUtility.GetEpcStringFromPcEPCData(data);
            AsReaderDevice device = AsReaderRFIDDevice.SharedInstance();
            dockManager.tagMemoryReceived = TagMemoryReceived;
            dockManager.writtenReceived = WrittenReceived;
            dockManager.errorReceived = ErrorReceived;
        }
        public override void ViewWillDisappear(bool animated)
        {
            base.ViewWillDisappear(animated);
            dockManager.tagMemoryReceived = null;
            dockManager.writtenReceived = null;
            dockManager.errorReceived = null;
        }
        void DidSetChannelParamReceived(int statusCode)
        {
            if (statusCode == 0)
            {
                Utils.ShowAlert("", "Changed Channel Data", this);
            }
        }
        private void keyboardWillShow(NSNotification notification)
        {
            if (olData.IsFirstResponder && this.View.Frame.Y >= 0)
            {
                setViewMoveUp(true);
            }
            else if (olData.IsFirstResponder && this.View.Frame.Y < 0)
            {
                setViewMoveUp(false);
            }
        }
        private void setViewMoveUp(bool moveUp)
        {
            if (moveUp)
            {
                UIView.Animate(0.2,
                    () =>
                    {
                        olScrollVeiw.ContentOffset = new CoreGraphics.CGPoint(0, 100);
                    });
            }
            else
            {
                UIView.Animate(0.2,
                   () =>
                   {
                       olScrollVeiw.ContentOffset = new CoreGraphics.CGPoint(0.0f, olScrollVeiw.Frame.Y - 80);
                   });
            }
        }
        private NSString dataToEpcInteger(NSData data)
        {
            byte[] pData = data.ToArray();
            Marshal.Copy(data.Bytes, pData, 0, Convert.ToInt32(data.Length));
            int intData = pData[0] << 8 | pData[1];
            intData = intData >> 11;
            return (NSString)intData.ToString();
        }
        bool ShouldReturn(UITextField textField)
        {
            setViewMoveUp(false);
            textField.ResignFirstResponder();
            return false;
        }
        private class ReadWriteDelegate : UITextFieldDelegate
        {
            public override bool ShouldChangeCharacters(UITextField textField, NSRange range, string replacementString)
            {
                string newString = textField.Text + replacementString;
                if (Utils.IsCorrectWriteData(newString))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }
        void TagMemoryReceived(NSData dat)
        {
            NSString strData;
            if (olTargetMemory.SelectedSegment == 1)
            {
                strData = dataToEpcInteger(dat);
            }
            else
            {
                strData = (NSString)EpcConverter.toHexString(dat); 
            }
            olData.Text = strData;
        }
        void WrittenReceived(int statusCode)
        {
            if (statusCode == 0x00)
            {   
                Utils.ShowAlert("Confirm", "Done Write.", this);
            }
        }
        void ErrorReceived(NSData errorCode)
        {
            byte[] ptr = errorCode.ToArray();
            Marshal.Copy(errorCode.Bytes, ptr, 0, Convert.ToInt32(errorCode.Length));
            string strErrCode = "";
            string strSubCode = "";
            switch (ptr[0])
            {
                case 0x09: strErrCode = "Failure to read the tag memory"; break;
                case 0x10: strErrCode = "Failure to write data"; break;
                case 0x0B: strErrCode = "Read Type C Tag ID Multiple’ in Operation"; break;
                case 0x0D: strErrCode = "Not in mode ‘Read Type C Tag ID Multiple’"; break;
                case 0x0E: strErrCode = "Invalid parameter"; break;
                case 0x12: strErrCode = "Failure to kill a tag"; break;
                case 0x13: strErrCode = "Failure to lock a tag"; break;
                case 0x15: strErrCode = "Failure to read a tag"; break;
                case 0x18: strErrCode = "Not supported command"; break;
                case 0xFF: strErrCode = "CRC Error"; break;
                default:
                    {
                        string strTem = "0x" + ptr[1];
                        strErrCode = strTem;
                    }
                    break;
            }
            switch (ptr[2])
            {
                case 0x01: strSubCode = " Not supported "; break;
                case 0x02: strSubCode = " Insufficient privileges"; break;
                case 0x03: strSubCode = " Memory overrun"; break;
                case 0x04: strSubCode = " Memory locked"; break;
                case 0x05: strSubCode = " Crypto suite error"; break;
                case 0x06: strSubCode = " Command not encapsulated"; break;
                case 0x07: strSubCode = " ResponseBuffer overflow"; break;
                case 0x08: strSubCode = " Security timeout"; break;
                case 0x0B: strSubCode = " Insufficient power"; break;
                case 0x0F: strSubCode = " Non- specific error"; break;
                case 0x11: strSubCode = " Sensor Scheduling configuration"; break;
                case 0x12: strSubCode = " Tag Busy"; break;
                case 0x13: strSubCode = " Measurement type not supported"; break;
                case 0x80: strSubCode = " No tag detected"; break;
                case 0x81: strSubCode = " Handle acquisition failure"; break;
                case 0x82: strSubCode = " Access password failure"; break;
                case 0x90: strSubCode = " CRC error"; break;
                case 0x91: strSubCode = " Rx Timeout"; break;
                case 0xA0: strSubCode = " Registry update failure"; break;
                case 0xA1: strSubCode = " Registry erase failure"; break;
                case 0xA2: strSubCode = " Registry write failure"; break;
                case 0xA3: strSubCode = " Registry not exist"; break;
                case 0xB0: strSubCode = " UART failure"; break;
                case 0xB1: strSubCode = " SPI failure"; break;
                case 0xB2: strSubCode = " I2C failure"; break;
                case 0xB3: strSubCode = " GPIO failure"; break;
                case 0xE0: strSubCode = " Not supported command"; break;
                case 0xE1: strSubCode = " Undefined command"; break;
                case 0xE2: strSubCode = " Invalid parameter"; break;
                case 0xE3: strSubCode = " Too high parameter"; break;
                case 0xE4: strSubCode = " Too low parameter"; break;
                case 0xE5: strSubCode = " Failure automatic read operation"; break;
                case 0xE6: strSubCode = " Not automatic read mode"; break;
                case 0xE7: strSubCode = " Failure to get last response"; break;
                case 0xE8: strSubCode = " Failure to control test"; break;
                case 0xE9: strSubCode = " Failure to reset Reader"; break;
                case 0xEA: strSubCode = " Rfidblock control failure"; break;
                case 0xEB: strSubCode = " Automatic read in operation"; break;
                case 0xF0: strSubCode = " Undefined other error"; break;
                case 0xF1: strSubCode = " Failure to verify write operation"; break;
                case 0xFC: strSubCode = " Abnormal antenna"; break;
                case 0xFF: strSubCode = " None error"; break;

                default:
                    {
                        string strTem = "0x" + ptr[2];
                        strSubCode = strTem;
                    }
                    break;
            }
            string strErrTotal = "Error Code(0x" + ptr[0] + ") :  " + strErrCode + " \n " + "SubError(0x" + ptr[2] + ") : " + strSubCode;
            Utils.ShowAlert("Error", strErrTotal, this);
        }
        partial void eModeChanged(UISegmentedControl sender)
        {
            if (olMode.SelectedSegment == 0)
            {
                NavigationItem.Title = "Read";
            }
            else
            {
                NavigationItem.Title = "Write";
            }
        }
        partial void rightBarButtonItemClicked(UIBarButtonItem sender)
        {
            olTargetEpc.ResignFirstResponder();
            olAccessPassword.ResignFirstResponder();
            olStartAdress.ResignFirstResponder();
            olLength.ResignFirstResponder();
            olData.ResignFirstResponder();
            setViewMoveUp(false);
            string hexaString = olAccessPassword.Text;
            int accesspassword = (int)(Utils.hexStringToLong(hexaString));
            int startAddress = 0;
            int.TryParse(olStartAdress.Text, out startAddress);
            int dataLength = 0;
            int.TryParse(olLength.Text, out dataLength);
            int membank = '\0';
            switch (olTargetMemory.SelectedSegment)
            {
                case 0:
                    membank = 0;
                    break;
                case 1:
                case 2:
                    membank = 1;
                    break;
                case 3:
                    membank = 2;
                    break;
                case 4:
                    membank = 3;
                    break;
            }
            NSData data = PhyUtility.hexStringToBytes((NSString)olData.Text);
            NSData epcs = PhyUtility.hexStringToBytes((NSString)olTargetEpc.Text);
            if (epcs.Length == 0 || epcs.Length < 2)
            {
                return;
            }
            NSRange range = new NSRange(0, 2);
            NSData pcData = epcs.Subdata(range);
            if (olMode.SelectedSegment == 0)
            {
                AsReaderRFIDDevice.SharedInstance().ReadTagWithAccessPassword(accesspassword, epcs, membank, startAddress, dataLength);
            }
            else
            {
                if (olTargetMemory.SelectedSegment == 1)
                {
                    byte[] ptr = new byte[pcData.Length];
                    Marshal.Copy(pcData.Bytes, ptr, 0, Convert.ToInt32(pcData.Length));
                    int intData = ptr[0] << 8 | ptr[1];
                    int epcLength = 0;
                    int.TryParse(olData.Text, out epcLength);
                    if (epcLength != 0)
                    {
                        intData = intData & 0x07FF;
                        intData |= (epcLength & 0x1F) << 11;
                    }
                    string intDataString = intData.ToString();
                    data = PhyUtility.hexStringToBytes((NSString)intDataString);
                }
                AsReaderRFIDDevice.SharedInstance().WriteTagMemoryWithAccessPassword(accesspassword, epcs, membank, startAddress, data);
            }
        }
        partial void eTargetMemoryChanged(UISegmentedControl sender)
        {
            olDataTitle.Text = "Data (HEX)";
            olData.ResignFirstResponder();
            olData.KeyboardType = UIKeyboardType.Default;
            if (olTargetMemory.SelectedSegment == 1)
            {
                olStartAdress.Text = "1";
                olLength.Text = "1";
                olStartAdress.Enabled = false;
                olLength.Enabled = false;
                olDataTitle.Text = "EPC Length";
                olData.KeyboardType = UIKeyboardType.NumberPad;
            }
            else if (olTargetMemory.SelectedSegment == 2)
            {
                olStartAdress.Text = "2";
                olLength.Text = "0";
                olStartAdress.Enabled = false;
                olLength.Enabled = false;
            }
            else
            {
                olStartAdress.Enabled = true;
                olLength.Enabled = true;
            }
        }
        partial void actLimitEPCLength(UITextField sender)
        {
            if (olTargetMemory.SelectedSegment == 1)
            {
                int eLength = 0;
                int.TryParse(olData.Text, out eLength);
                if (eLength > 31)
                {
                    olData.Text = "31";
                }
            }
        }
    }
}
