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

using System;
using Foundation;
using UIKit;
using AsReaderDock4;

namespace AsReaderDock_VS
{
	public partial class NFCWriteViewController : UIViewController
	{
        AsReaderNFCDevice device = AsReaderDockManager.sharedInstance().nfcDevice;
        ModelSettings m_Model = ModelSettings.sharedInstance();
        AsReaderDockManager dockManager = AsReaderDockManager.sharedInstance();

        public enum NFCWriteOptions : int
        {
            WriteSingleBlock = 0,
            WriteBytes,
        }

        NFCWriteOptions nfcWriteOptions = NFCWriteOptions.WriteSingleBlock;

        public NFCWriteViewController (IntPtr handle) : base (handle)
		{
		}

        public override void ViewDidLoad()
        {
            base.ViewDidLoad();
            writeButton.Layer.MasksToBounds = true;
            writeButton.Layer.CornerRadius = 5;
            NSDictionary dic = m_Model.m_arReadTagData.GetItem<NSDictionary>((nuint)m_Model.m_nSelectTagNum);
            NSString UIDStr = (NSString)dic.ObjectForKey(GlobalDefine.df_CELL_TAG_INFO);

            writeDataTextFiled.Delegate = new MyUITextFieldDelegate(this);

            string str = UIDStr.ToString();
            string appendStr = "";
            for (int i = 1; i < 9; i++)
            {
                appendStr += str.Substring(str.Length-i * 2, 2);
            }
            uidTextField.Text = appendStr.ToUpper();
            segmentControl.SelectedSegment = 0;
            NfcWriteParamsExplain();
        }
        public override void ViewWillAppear(bool animated)
        {
            base.ViewWillAppear(animated);

            dockManager.nfcWriteSingleBlockStatusCode = NfcWriteSingleBlockStatusCode;
            dockManager.nfcWriteBytesStatusCode = NfcWriteBytesStatusCode;
        }
        public override void ViewDidDisappear(bool animated)
        {
            base.ViewDidDisappear(animated);
            dockManager.nfcWriteSingleBlockStatusCode = null;
            dockManager.nfcWriteBytesStatusCode = null;
        }
        public override void TouchesBegan(NSSet touches, UIEvent evt)
        {
            View.EndEditing(true);
        }
        partial void onClickWriteButton(UIButton sender)
        {
            View.EndEditing(true);
            if (!Utils.CheckNumberTextLength(blockIndexTextField.Text, 255, 0))
            {
                Utils.ShowAlert("", "The value of the block index is in the range 0 - 255.Please enter a valid value", this);
            }
            else
            {
                int blockIndex = int.Parse(blockIndexTextField.Text);
                NSData UIDData = Utils.ConvertHexStrToData(new NSString(uidTextField.Text));
                NSData writeData = Utils.ConvertHexStrToData(new NSString(writeDataTextFiled.Text));

                switch (nfcWriteOptions)
                {
                    case NFCWriteOptions.WriteSingleBlock:
                        device.WriteSingleBlockWithBlockIndex(blockIndex, writeData, UIDData);
                        break;
                    case NFCWriteOptions.WriteBytes:
                        device.WriteBytesWithBlockIndex(blockIndex, writeData, UIDData);
                        break;
                }
            }

        }
        partial void onClickSegment(UISegmentedControl sender)
        {
            switch (sender.SelectedSegment)
            {
                case 0:
                    nfcWriteOptions = NFCWriteOptions.WriteSingleBlock;
                    break;
                case 1:
                    nfcWriteOptions = NFCWriteOptions.WriteBytes;
                    break;
            }
            NfcWriteParamsExplain();

        }

        void NfcWriteSingleBlockStatusCode(SDK4StatusCode statusCode)
        {
            CheckStatusCode(statusCode);
        }
        void NfcWriteBytesStatusCode(SDK4StatusCode statusCode)
        {
            CheckStatusCode(statusCode);
        }
        void CheckStatusCode(SDK4StatusCode statusCode)
        {
            if (statusCode == SDK4StatusCode.Ok)
            {
                Utils.ShowAlert("Write Success", null, this);
            }
            else
            {
                
                string code = "0";
                switch (statusCode)
                {
                    case SDK4StatusCode.Ok:
                        code = "0";
                        break;
                    case SDK4StatusCode.TimeOvr:
                        code = "02";
                        break;
                    case SDK4StatusCode.Err:
                        code = "07";
                        break;
                    case SDK4StatusCode.ErrWrite:
                        code = "09";
                        break;
                    case SDK4StatusCode.ProtectOperate:
                        code = "0a";
                        break;
                    case SDK4StatusCode.DatanumErr:
                        code = "41";
                        break;
                    case SDK4StatusCode.SumErr:
                        code = "42";
                        break;
                    case SDK4StatusCode.CmdErr:
                        code = "44";
                        break;
                    case SDK4StatusCode.AdrsErr:
                        code = "49";
                        break;
                    case SDK4StatusCode.RdmBlocksErr:
                        code = "4c";
                        break;
                    case SDK4StatusCode.NoUid:
                        code = "4d";
                        break;
                    case SDK4StatusCode.UidPosErr:
                        code = "4e";
                        break;
                    case SDK4StatusCode.UidNumErr:
                        code = "4f";
                        break;
                    case SDK4StatusCode.SystemErr:
                        code = "f1";
                        break;
                    default:
                        break;
                }
                Utils.ShowAlert("Write Failed", "StatusCode: " + String.Format("0x{0:X000}", (int)statusCode), this);
            }
        }

        private void NfcWriteParamsExplain()
        {
            switch (nfcWriteOptions)
            {
                case NFCWriteOptions.WriteBytes:
                    explainTextView.Text = "Writes data to the specified Block area of the NFC tag. If the length of the written data (bytes) is less than the size of the target Block area, the rest of the area will be filled with 0 automatically; and if the length of the write exceeds the size of the target Block area, the rest of the data is automatically written to the next Block area, and so on.";
                    break;
                case NFCWriteOptions.WriteSingleBlock:
                    explainTextView.Text = "Writes data to the specified Block area of the NFC tag, requiring the length（bytes） of the written data equaling the length of the target Block area.";
                    break;
            }
        }

        class MyUITextFieldDelegate : UITextFieldDelegate
        {
            readonly NFCWriteViewController viewController;

            public MyUITextFieldDelegate(NFCWriteViewController _viewController)
            {
                viewController = _viewController;
            }
            public override bool ShouldChangeCharacters(UITextField textField, NSRange range, string replacementString)
            {
                return Utils.IsCorrectWriteData(textField.Text + replacementString);
            }
        }
    }
}
