using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using Android.App;
using Android.Content;
using Android.Icu.Text;
using Android.OS;
using Android.Runtime;
using Android.Util;
using Android.Views;
using Android.Widget;
using FiscalPrinterSDK;
using Java.Util;

namespace GetEJDocuments_DevGr_B
{
    public class ElectronicJournalFragment : Android.Support.V4.App.Fragment
    {
        Button button;
        private View fView;
        private string document_Type = "0";
        public string sum = "0.00";
        private bool StopReading = false;
        private List<string> lstTitles = new List<string>();
        private List<string[]> rej = new List<string[]>();
        ListView lstReceiptsContainer;
        List<string> list = new List<string>();
        ProgressBar prgAction;
        public override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            // Create your fragment here
        }

        public static ElectronicJournalFragment NewInstance()
        {
            var detailsFrag = new ElectronicJournalFragment { Arguments = new Bundle() };
            return detailsFrag;
        }

        public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
        {
            if (container == null)
            {
                // Currently in a layout without a container, so no reason to create our view.
                return null;
            }
            // Use this to return your custom view for this Fragment
            // return inflater.Inflate(Resource.Layout.YourFragment, container, false);
            fView = inflater.Inflate(Resource.Layout.ElectronicJournal, container, false);
            if (MainActivity.fiscal != null) fView.FindViewById<Spinner>(Resource.Id.spinner).SetSelection(0);
            button = fView.FindViewById<Button>(Resource.Id.btnSelectStartDate);
            fView.FindViewById<Button>(Resource.Id.btnSelectStartDate).Click += BtnSelectStartDate_Click;
            button = fView.FindViewById<Button>(Resource.Id.btnSelectStartTime);
            fView.FindViewById<Button>(Resource.Id.btnSelectStartTime).Click += BtnSelectStartTime_Click;
            button = fView.FindViewById<Button>(Resource.Id.btnSelectEndDate);
            fView.FindViewById<Button>(Resource.Id.btnSelectEndDate).Click += BtnSelectEndDate_Click;
            button = fView.FindViewById<Button>(Resource.Id.btnSelectEndTime);
            fView.FindViewById<Button>(Resource.Id.btnSelectEndTime).Click += BtnSelectEndTime_Click;
            button = fView.FindViewById<Button>(Resource.Id.btnReadEJDocs);
            fView.FindViewById<Button>(Resource.Id.btnReadEJDocs).Click += BtnReadEJDocs_Click;
            button = fView.FindViewById<Button>(Resource.Id.btnPrintDocs);
            fView.FindViewById<Button>(Resource.Id.btnPrintDocs).Click += BtnPrintDocs_Click;
            button = fView.FindViewById<Button>(Resource.Id.btnStop);
            fView.FindViewById<Button>(Resource.Id.btnStop).Click += BtnStop_Click;
            button = fView.FindViewById<Button>(Resource.Id.btnReadStructured);
            fView.FindViewById<Button>(Resource.Id.btnReadStructured).Click += BtnReadStructured_Click;
            prgAction = (ProgressBar)fView.FindViewById(Resource.Id.progressBar1);
            prgAction.Visibility = Android.Views.ViewStates.Invisible;
            fView.FindViewById<CheckBox>(Resource.Id.chkByDocNum).Click += ChkByDocNum_Click;
            fView.FindViewById<CheckBox>(Resource.Id.chkByZNum).Click += ChkByZNum_Click;
            DateTime startDate = DateTime.Today.AddDays(-1).Date;
            DateTime endDate = DateTime.Today.Date;
            fView.FindViewById<EditText>(Resource.Id.txtStartDate).Text = startDate.ToString("ddMMyy");
            fView.FindViewById<EditText>(Resource.Id.txtEndDate).Text = endDate.ToString("ddMMyy");
            fView.FindViewById<EditText>(Resource.Id.txtEndTime).Text = "230000";
            fView.FindViewById<EditText>(Resource.Id.txtStartTime).Text = "235959";
            lstReceiptsContainer = fView.FindViewById<ListView>(Resource.Id.lstReceipts);
            lstReceiptsContainer.ItemClick += LstReceiptsContainer_ItemClick;
            Calculate_Controls();
            return fView;
        }

        private string GetReceiptText(int pos, List<string[]> r)
        {
            string result = "";
            for (int i = 0; i < r[pos].Length; i++)
            {
                result += r[pos][i];
            }
            return result;
        }

        private void LstReceiptsContainer_ItemClick(object sender, AdapterView.ItemClickEventArgs e)
        {

            RecEJContentDialog fmEJContent = new RecEJContentDialog(MainActivity.GetInstance());
            fmEJContent.lstPosition = e.Position;
            fmEJContent.OnExecuteReceiptEJText += FmEJContent_OnExecuteReceiptEJText;
            fmEJContent.Show();
            fView.FindViewById<EditText>(Resource.Id.txtToNum).FocusSearch(FocusSearchDirection.Down);
        }


        private string FmEJContent_OnExecuteReceiptEJText(int position)
        {
            return GetReceiptText(position, rej);
        }


        DateTime startDate = DateTime.Today.AddDays(-1).Date;
        DateTime endDate = DateTime.Today.Date;

        private void ChkRangeByNum_Change()
        {
            if (fView == null) return;
            fView.FindViewById<CheckBox>(Resource.Id.chkByDocNum).Enabled = true;
            fView.FindViewById<CheckBox>(Resource.Id.chkByZNum).Enabled = true;

            if (fView.FindViewById<CheckBox>(Resource.Id.chkByDocNum).Checked)
            {
                fView.FindViewById<TextView>(Resource.Id.lblFromNum).Enabled = fView.FindViewById<CheckBox>(Resource.Id.chkByDocNum).Checked;
                fView.FindViewById<TextView>(Resource.Id.lblToNum).Enabled = fView.FindViewById<CheckBox>(Resource.Id.chkByDocNum).Checked;
                fView.FindViewById<EditText>(Resource.Id.txtFromNum).Enabled = fView.FindViewById<CheckBox>(Resource.Id.chkByDocNum).Checked;
                fView.FindViewById<EditText>(Resource.Id.txtToNum).Enabled = fView.FindViewById<CheckBox>(Resource.Id.chkByDocNum).Checked;
                fView.FindViewById<TextView>(Resource.Id.lblFromZNum).Enabled = false;
                fView.FindViewById<TextView>(Resource.Id.lblToZNum).Enabled = false;
                fView.FindViewById<EditText>(Resource.Id.txtFromZNum).Enabled = false;
                fView.FindViewById<EditText>(Resource.Id.txtToZNum).Enabled = false;
                fView.FindViewById<Button>(Resource.Id.btnSelectStartDate).Enabled = !fView.FindViewById<CheckBox>(Resource.Id.chkByDocNum).Checked;
                fView.FindViewById<Button>(Resource.Id.btnSelectStartTime).Enabled = !fView.FindViewById<CheckBox>(Resource.Id.chkByDocNum).Checked;
                fView.FindViewById<Button>(Resource.Id.btnSelectEndDate).Enabled = !fView.FindViewById<CheckBox>(Resource.Id.chkByDocNum).Checked;
                fView.FindViewById<Button>(Resource.Id.btnSelectEndTime).Enabled = !fView.FindViewById<CheckBox>(Resource.Id.chkByDocNum).Checked;


            }
            else if (fView.FindViewById<CheckBox>(Resource.Id.chkByZNum).Checked)
            {
                fView.FindViewById<TextView>(Resource.Id.lblFromZNum).Enabled = true;
                fView.FindViewById<TextView>(Resource.Id.lblToZNum).Enabled = true;
                fView.FindViewById<EditText>(Resource.Id.txtFromZNum).Enabled = true;
                fView.FindViewById<EditText>(Resource.Id.txtToZNum).Enabled = true;
                fView.FindViewById<TextView>(Resource.Id.lblFromNum).Enabled = false;
                fView.FindViewById<TextView>(Resource.Id.lblToNum).Enabled = false;
                fView.FindViewById<EditText>(Resource.Id.txtFromNum).Enabled = false;
                fView.FindViewById<EditText>(Resource.Id.txtToNum).Enabled = false;
                fView.FindViewById<Button>(Resource.Id.btnSelectStartDate).Enabled = !fView.FindViewById<CheckBox>(Resource.Id.chkByZNum).Checked;
                fView.FindViewById<Button>(Resource.Id.btnSelectStartTime).Enabled = !fView.FindViewById<CheckBox>(Resource.Id.chkByZNum).Checked;
                fView.FindViewById<Button>(Resource.Id.btnSelectEndDate).Enabled = !fView.FindViewById<CheckBox>(Resource.Id.chkByZNum).Checked;
                fView.FindViewById<Button>(Resource.Id.btnSelectEndTime).Enabled = !fView.FindViewById<CheckBox>(Resource.Id.chkByZNum).Checked;
            }
            else
            {
                fView.FindViewById<Button>(Resource.Id.btnSelectStartDate).Enabled = true;
                fView.FindViewById<Button>(Resource.Id.btnSelectStartTime).Enabled = true;
                fView.FindViewById<Button>(Resource.Id.btnSelectEndDate).Enabled = true;
                fView.FindViewById<Button>(Resource.Id.btnSelectEndTime).Enabled = true;

                fView.FindViewById<TextView>(Resource.Id.lblFromZNum).Enabled = false;
                fView.FindViewById<TextView>(Resource.Id.lblFromNum).Enabled = false;
                fView.FindViewById<TextView>(Resource.Id.lblToZNum).Enabled = false;
                fView.FindViewById<TextView>(Resource.Id.lblToNum).Enabled = false;
                fView.FindViewById<EditText>(Resource.Id.txtFromZNum).Enabled = false;
                fView.FindViewById<EditText>(Resource.Id.txtFromNum).Enabled = false;
                fView.FindViewById<EditText>(Resource.Id.txtToNum).Enabled = false;
                fView.FindViewById<EditText>(Resource.Id.txtToZNum).Enabled = false;

            }
        }

        private void ChkByDocNum_Click(object sender, EventArgs e)
        {
            ChkRangeByNum_Change();
        }

        private void ChkByZNum_Click(object sender, EventArgs e)
        {
            ChkRangeByNum_Change();
        }

        private void BtnSelectStartDate_Click(object sender, EventArgs e)
        {
            DatePickerFragment fr = DatePickerFragment.NewInstance(delegate (DateTime date)
            {
                fView.FindViewById<TextView>(Resource.Id.txtStartDate).Text = date.ToString("ddMMyy");
                startDate = date;
            });
            fr.Show(FragmentManager, DatePickerFragment.TAG);
        }

        private void BtnSelectStartTime_Click(object sender, EventArgs e)
        {
            TimePickerFragment frag = TimePickerFragment.NewInstance(
         delegate (DateTime time)
         {
             fView.FindViewById<TextView>(Resource.Id.txtStartTime).Text = time.ToString("HHmmss");
         });

            frag.Show(FragmentManager, TimePickerFragment.TAG);
        }

        private void ExecuteFiscalCodeWithThread(Action func)
        {
            System.Threading.ThreadPool.QueueUserWorkItem(delegate
            {
                this.Activity.RunOnUiThread(() => // BeginInvoke 
                {
                    ManageEJControls(false);
                });
                try
                {
                    func();
                }
                catch (FiscalException s)
                {
                    this.Activity.RunOnUiThread(() =>
                    {
                        if (s.ErrorCode == -23) CheckStatusErrorProperties();    // error in status bytes
                        else MainActivity.ShowMessage("Operation failed: " + s.Message, "Error");
                    });
                }
                catch (Exception ex)
                {
                    this.Activity.RunOnUiThread(() =>
                    {
                        MainActivity.ShowMessage("Operation failed: " + ex.Message, "Error");
                    });
                }
                finally
                {
                    this.Activity.RunOnUiThread(() =>
                    {
                        //CheckStatusErrorProperties();
                        prgAction.Visibility = Android.Views.ViewStates.Invisible;
                        ManageEJControls(true);
                        Calculate_Controls();
                    });
                }
            }, null);
        }

        private void ExecuteFiscalCode(Action func)
        {
            ManageEJControls(false);
            try
            {
                func();
            }
            catch (FiscalException s)
            {
                if (s.ErrorCode == -23) // error in status bytes

                    if (CheckStatusErrorProperties()) return;
                if (s.ErrorCode != 0) MainActivity.ShowMessage("Operation failed: " + s.Message, "Error");
            }
            catch (Exception ex)
            {
                MainActivity.ShowMessage("Operation failed: " + ex.Message, "Error");
            }
            finally
            {
                // CheckStatusErrorProperties();
                prgAction.Visibility = Android.Views.ViewStates.Invisible;
                ManageEJControls(true);
                Calculate_Controls();
            }
        }

        private bool CheckStatusErrorProperties()
        {
            string msg = "";
            try
            {
                if (MainActivity.fiscal.eSBit_GeneralError_Sharp) msg = MainActivity.fiscal.GetErrorMessage("-29");
                if (MainActivity.fiscal.eSBit_ClockIsNotSynchronized) msg = msg + "\r\n" + MainActivity.fiscal.GetErrorMessage("-26");
                if (MainActivity.fiscal.eSBit_CommandCodeIsInvalid) msg = msg + "\r\n" + MainActivity.fiscal.GetErrorMessage("-25");
                if (MainActivity.fiscal.eSBit_SyntaxError) msg = msg + "\r\n" + MainActivity.fiscal.GetErrorMessage("-24");
                if (MainActivity.fiscal.eSBit_BuildInTaxTerminalNotResponding) msg = msg + "\r\n" + MainActivity.fiscal.GetErrorMessage("-50");
                if (MainActivity.fiscal.eSBit_CommandNotPermitted) msg = msg + "\r\n" + MainActivity.fiscal.GetErrorMessage("-32");
                if (MainActivity.fiscal.eSBit_Overflow) msg = msg + "\r\n" + MainActivity.fiscal.GetErrorMessage("-33");
                if (MainActivity.fiscal.eSBit_EJIsFull) msg = msg + "\r\n" + MainActivity.fiscal.GetErrorMessage("-37");
                if (MainActivity.fiscal.eSBit_EndOfPaper) msg = msg + "\r\n" + MainActivity.fiscal.GetErrorMessage("-39");
                if (MainActivity.fiscal.eSBit_FM_NotAccess) msg = msg + "\r\n" + MainActivity.fiscal.GetErrorMessage("-46");
                if (MainActivity.fiscal.eSBit_FM_Full) msg = msg + "\r\n" + MainActivity.fiscal.GetErrorMessage("-42");
                if (MainActivity.fiscal.eSBit_GeneralError_Star) msg = msg + "\r\n" + MainActivity.fiscal.GetErrorMessage("-41");
                if (msg != "")
                {
                    MainActivity.ShowMessage("Status bits error(s):\r\n" + msg + "\r\n For more info check 'Status bytes' section", "Warning");
                    return true;
                }
                return false;
            }
            catch (Exception ex)
            {
                MainActivity.ShowMessage("Operation failed: " + ex.Message, "Error");
                return true;

            }
        }

        private void BtnSelectEndDate_Click(object sender, EventArgs e)
        {
            DatePickerFragment fr = DatePickerFragment.NewInstance(delegate (DateTime date)
            {
                fView.FindViewById<TextView>(Resource.Id.txtEndDate).Text = date.ToString("ddMMyy");
                startDate = date;
            });
            fr.Show(FragmentManager, DatePickerFragment.TAG);
        }

        private void BtnSelectEndTime_Click(object sender, EventArgs e)
        {
            TimePickerFragment frag = TimePickerFragment.NewInstance(
         delegate (DateTime time)
         {
             fView.FindViewById<TextView>(Resource.Id.txtEndTime).Text = time.ToString("HHmmss");
         });

            frag.Show(FragmentManager, TimePickerFragment.TAG);
        }

        private void ManageEJControls(bool value)
        {
            if (fView != null)
            {
                fView.FindViewById<Button>(Resource.Id.btnReadEJDocs).Enabled = value;
                fView.FindViewById<Button>(Resource.Id.btnPrintDocs).Enabled = value;
                fView.FindViewById<Button>(Resource.Id.btnStop).Enabled = !value;
                fView.FindViewById<Button>(Resource.Id.btnReadStructured).Enabled = value;
                fView.FindViewById<Button>(Resource.Id.btnSelectStartDate).Enabled = value;
                fView.FindViewById<Button>(Resource.Id.btnSelectStartTime).Enabled = value;
                fView.FindViewById<Button>(Resource.Id.btnSelectEndDate).Enabled = value;
                fView.FindViewById<Button>(Resource.Id.btnSelectEndTime).Enabled = value;
                fView.FindViewById<Spinner>(Resource.Id.spinner).Enabled = value;
                fView.FindViewById<TextView>(Resource.Id.lblDocType).Enabled = value;
                fView.FindViewById<EditText>(Resource.Id.txtStartDate).Enabled = value;
                fView.FindViewById<EditText>(Resource.Id.txtStartTime).Enabled = value;
                fView.FindViewById<EditText>(Resource.Id.txtEndTime).Enabled = value;
                fView.FindViewById<EditText>(Resource.Id.txtEndDate).Enabled = value;
                fView.FindViewById<CheckBox>(Resource.Id.chkByDocNum).Enabled = value;
                fView.FindViewById<CheckBox>(Resource.Id.chkByZNum).Enabled = value;
                fView.FindViewById<TextView>(Resource.Id.lblFromZNum).Enabled = value;
                fView.FindViewById<TextView>(Resource.Id.lblFromNum).Enabled = value;
                fView.FindViewById<TextView>(Resource.Id.lblToZNum).Enabled = value;
                fView.FindViewById<TextView>(Resource.Id.lblToNum).Enabled = value;
                fView.FindViewById<EditText>(Resource.Id.txtFromZNum).Enabled = value;
                fView.FindViewById<EditText>(Resource.Id.txtFromNum).Enabled = value;
                fView.FindViewById<EditText>(Resource.Id.txtToNum).Enabled = value;
                fView.FindViewById<EditText>(Resource.Id.txtToZNum).Enabled = value;
            }
        }

        private bool checkDocumentNumsBoxes()
        {
            string txtToZ = fView.FindViewById<EditText>(Resource.Id.txtToZNum).Text;
            string txtFromZ = fView.FindViewById<EditText>(Resource.Id.txtFromZNum).Text;
            string txtToNum = fView.FindViewById<EditText>(Resource.Id.txtToNum).Text;
            string txtFromNum = fView.FindViewById<EditText>(Resource.Id.txtFromNum).Text;
            if (fView.FindViewById<EditText>(Resource.Id.txtToZNum).Enabled)
            {
                if (txtToZ == "") txtToZ = txtFromZ;
            }
            if (fView.FindViewById<CheckBox>(Resource.Id.chkByZNum).Enabled)
            {
                if (!fView.FindViewById<CheckBox>(Resource.Id.chkByZNum).Checked)
                {
                    if (fView.FindViewById<EditText>(Resource.Id.txtFromNum).Text == "")   // TODO: тук може да е само един номер
                    {
                        MainActivity.ShowMessage("You need to enter data for document numbers!", "Alert");
                        if (fView.FindViewById<EditText>(Resource.Id.txtFromNum).Enabled) fView.FindViewById<EditText>(Resource.Id.txtFromNum).RequestFocus();
                        return false;
                    }
                }
                else
                {
                    if (String.IsNullOrEmpty(fView.FindViewById<EditText>(Resource.Id.txtFromZNum).Text))
                    {
                        MainActivity.ShowMessage("You need to enter data for Z report numbers!", "Alert");
                        if (fView.FindViewById<EditText>(Resource.Id.txtFromZNum).Enabled && fView.FindViewById<EditText>(Resource.Id.txtToZNum).Enabled) fView.FindViewById<EditText>(Resource.Id.txtFromZNum).RequestFocus();
                        return false;
                    }
                }
            }
            else
            {
                if (String.IsNullOrEmpty(fView.FindViewById<EditText>(Resource.Id.txtFromNum).Text))   // TODO: тук може да е само един номер
                {
                    MainActivity.ShowMessage("You need to enter data for document numbers!", "Alert");
                    if (fView.FindViewById<EditText>(Resource.Id.txtFromNum).Enabled) fView.FindViewById<EditText>(Resource.Id.txtFromNum).RequestFocus();
                    return false;
                }
            }
            if (txtToNum == "") fView.FindViewById<EditText>(Resource.Id.txtToNum).Text = txtFromNum;

            //if (fView.FindViewById<EditText>(Resource.Id.txtFromNum).Enabled)
            //{
            if (Int32.Parse(txtFromNum) > Int32.Parse(txtToNum))
            {
                MainActivity.ShowMessage("Your 'From number' field value need to be smaller than 'To number' value!", "Warning");
                if (fView.FindViewById<EditText>(Resource.Id.txtFromNum).Enabled) fView.FindViewById<EditText>(Resource.Id.txtFromNum).RequestFocus();
                return false;
            }
            // }
            return true;
        }

        /*private void ReadDocsByZNums_DeviceGroup_A(string startZNum, string endZNum, string startNum, string endNum)
        {
            int error_Code = 0;
            int i, stNumber, endNumber, stZNumber, endZNumber;
            string ffAnswer = "";

            if (MainActivity.fiscal == null) return;
            if (!MainActivity.fiscal.device_Connected) return;
            if (fView == null) return;

            stNumber = Int32.Parse(startNum);
            endNumber = Int32.Parse(endNum);
            stZNumber = Int32.Parse(startZNum);
            endZNumber = Int32.Parse(endZNum);
            // string inputValue = "", outputValue = "";
            try
            {
                Calculate_DocumentType();
                for (i = stZNumber; i <= endZNumber; i++)
                {
                    if (StopReading) break;
                    //inputValue = "R,#" + document_Type + ",*" + i.ToString() + "," + startNum + "," + endNum; // custom command
                    if (StopReading) break;

                    var result = MainActivity.fiscal.klen_Set_DocsRange_InZReport("R", document_Type, i.ToString(), startNum, endNum);
                    //error_Code = serv.execute_Command(119, inputValue, ref outputValue);
                    if (result["fAnswer"] != "P") return;

                    else
                    {
                        list.Add(result["fRow"] + "\r\n");
                        if (!ReadLines_Loop()) break;

                    }

                }

            }
            catch (Exception ex)
            {
                MainActivity.ShowMessage(ex.Message, "Error");
            }



        }

        private void ReadDocsByNums_DeviceGroupA(string startNum, string endNum)
        {
            int error_Code = 0;
            //int i,stNumber, endNumber;
            string ffAnswer = "";
            //string inputValue = "", outputValue = "";

            if (MainActivity.fiscal == null) return;
            if (!MainActivity.fiscal.device_Connected) return;
            if (fView == null) return;
            //stNumber = Int32.Parse(startNum);
            // endNumber = Int32.Parse(endNum);
            try
            {
                Calculate_DocumentType();
                if (StopReading) return;
                var result = MainActivity.fiscal.klen_Set_DocsRange("R", document_Type, startNum, endNum);
                //inputValue = "R,#" + document_Type + "," + startNum + "," + endNum;
                //error_Code = serv.execute_Command(119, inputValue, ref outputValue);
                if (result["fAnswer"] != "P")
                {
                    this.Activity.RunOnUiThread(() =>
                    {
                        prgAction.Visibility = Android.Views.ViewStates.Invisible;
                    });
                    return;
                }

                else
                {
                    list.Add(result["fRow"] + "\r\n");
                    if (!ReadLines_Loop()) return;
                }

            }
            catch (Exception s)
            {
                throw;
                //MainActivity.ShowMessage(s.Message,"Error");
            }
        }
       */

        private void BtnReadEJDocs_Click(object sender, EventArgs e)
        {
            string fromDate = "", toDate = "", fromTime = "", toTime = "", fromDT = "", ToDT = "";
            if (MainActivity.fiscal == null) return;
            if (!MainActivity.fiscal.device_Connected) return;
            if (fView == null) return;
            fView.FindViewById<ListView>(Resource.Id.lstReceipts).Adapter = null;

            StopReading = false;
            Calculate_DocumentType();
            //id = 0;
            lstTitles.Clear();
            rej.Clear();
            list.Clear();
            ManageEJControls(false);

            ExecuteFiscalCode(() =>
                    {

                        prgAction.Visibility = Android.Views.ViewStates.Visible;

                        if (fView.FindViewById<CheckBox>(Resource.Id.chkByDocNum).Checked)
                        {
                            if (!checkDocumentNumsBoxes()) return;
                            if (fView.FindViewById<EditText>(Resource.Id.txtToZNum).Enabled)
                            {
                                if (fView.FindViewById<EditText>(Resource.Id.txtFromZNum).Text != "")
                                {
                                    //                        string txtToNum = fView.FindViewById<EditText>(Resource.Id.txtToNum).Text;
                                    //                        string txtFromNum = fView.FindViewById<EditText>(Resource.Id.txtFromNum).Text;
                                    string txtToZ = fView.FindViewById<EditText>(Resource.Id.txtToZNum).Text;
                                    string txtFromZ = fView.FindViewById<EditText>(Resource.Id.txtFromZNum).Text;

                                    ExecuteFiscalCodeWithThread(() =>
                                {
                                    ReadDocsByZNums_DeviceGroup_B(txtFromZ, txtToZ);
                                });
                                }

                            }
                            //                //else return;
                            else
                            {
                                string txtToNum = fView.FindViewById<EditText>(Resource.Id.txtToNum).Text;
                                string txtFromNum = fView.FindViewById<EditText>(Resource.Id.txtFromNum).Text;
                                ExecuteFiscalCodeWithThread(() =>
                                {
                                    ReadDocsByNums_DeviceGroup_B(txtFromNum, txtToNum);
                                });
                            }
                        }
                        else
                        {


                            fromDate = String.Format("{0:ddMMyy}", fView.FindViewById<EditText>(Resource.Id.txtStartDate).Text); // start date in format "ddMMyy"
                            toDate = String.Format("{0:ddMMyy}", fView.FindViewById<EditText>(Resource.Id.txtEndDate).Text);// end date in format "ddMMyy"
                            fromTime = String.Format("{0:HHmmss}", fView.FindViewById<EditText>(Resource.Id.txtStartTime).Text); // start time in format "HHmmss"
                            toTime = String.Format("{0:HHmmss}", fView.FindViewById<EditText>(Resource.Id.txtEndTime).Text);// end time in format "HHmmss"
                            fromDT = fromDate + fromTime;
                            ToDT = toDate + toTime;
                            //inputValue = "R," + document_Type + "," + fromDT + "," + ToDT;
                            //---------------------

                            if (!Check_DateTime(fromDate, toDate, fromTime, toTime)) return;
                            ExecuteFiscalCodeWithThread(() =>
                            {
                                var result = MainActivity.fiscal.klen_FindRange_ByDateTime("D", document_Type, fromDT, ToDT);
                                // error_Code = fiscal.CustomCommand(119, inputValue);
                                if (result["errorCode"] != "P")
                                {
                                    this.Activity.RunOnUiThread(() =>
                                    {
                                        prgAction.Visibility = Android.Views.ViewStates.Invisible;
                                    });
                                    return;
                                }
                                else
                                {
                                    if (result["firstDocumentNumber"] == "" || result["lastDocumentNumber"] == "") return;
                                    string firstDocNum = result["firstDocumentNumber"];
                                    string lastDocNum = result["lastDocumentNumber"];
                                    for (int j = Int32.Parse(firstDocNum); j <= Int32.Parse(lastDocNum); j++)
                                    {
                                        if (StopReading) break;
                                        var res = MainActivity.fiscal.klen_Prepare_DocumentInRange("0", j.ToString(), document_Type, result["lastDocumentNumber"]);
                                        if (res["errorCode"] != "P")
                                        {
                                            if (res["documentNumber"] != "")
                                            {
                                                if (j != Int32.Parse(res["documentNumber"])) continue;
                                            }
                                            else return;
                                        }
                                        else
                                        {
                                            if (!ReadLines_Loop_DeviceGroup_B())
                                            {
                                                lstTitles.Add(res["documentNumber"]);
                                                rej.Add(list.ToArray());
                                                list.Clear();
                                                this.Activity.RunOnUiThread(() =>
                                                {

                                                    lstReceiptsContainer.Adapter = new ArrayAdapter(MainActivity.GetInstance(), Resource.Layout.RecList_Item, lstTitles.ToArray());
                                                    
                                                });
                                               // return;
                                            }
                                        }
                                    }
                                    
                                }
                            });
                        }
                    });
        }

        private void ReadDocsByNums_DeviceGroup_B(string fromNum, string toNum)
        {
            int i, stNumber, endNumber;

            stNumber = Int32.Parse(fromNum);
            endNumber = Int32.Parse(toNum);

            try
            {
                Calculate_DocumentType();

                this.Activity.RunOnUiThread(() =>
                {
                    prgAction.Visibility = Android.Views.ViewStates.Visible;
                });

                for (i = stNumber; i <= endNumber; i++)
                {
                    var result = MainActivity.fiscal.klen_Prepare_DocumentInRange("0", i.ToString(), document_Type, toNum);
                    if (result["errorCode"] != "P")
                    {
                        if (result["documentNumber"] != "")
                        {
                            if (i != Int32.Parse(result["documentNumber"])) continue;
                        }
                        else return;
                    }
                    else
                    {
                        if (StopReading) break;
                        if (!ReadLines_Loop_DeviceGroup_B())
                        {
                            lstTitles.Add(result["documentNumber"]);
                            rej.Add(list.ToArray());
                            list.Clear();
                            this.Activity.RunOnUiThread(() =>
                            {
                                lstReceiptsContainer.Adapter = new ArrayAdapter(MainActivity.GetInstance(), Resource.Layout.RecList_Item, lstTitles.ToArray());

                            });
                            // return;
                        }
                    }
                }
               
                this.Activity.RunOnUiThread(() =>
                {
                    prgAction.Visibility = Android.Views.ViewStates.Invisible;
                });

            }
            catch (Exception ex)
            {
                throw;
            }
        }

        private void ReadDocsByZNums_DeviceGroup_B(string fromZ, string toZ)
        {
            int j, stZNumber, endZNumber;
            string firstDocNum = "", lastDocNum = "";


            stZNumber = Int32.Parse(fromZ);
            endZNumber = Int32.Parse(toZ);
            // string inputValue = "", outputValue = "";
            try
            {

                var result = MainActivity.fiscal.klen_FindRange_ByZReports("Z", document_Type, fromZ, toZ);
                if (result["errorCode"] != "P") return;

                else
                {
                    if (result["firstDocumentNumber"] == "" || result["lastDocumentNumber"] == "") return;

                    firstDocNum = result["firstDocumentNumber"];
                    lastDocNum = result["lastDocumentNumber"];
                    for (j = Int32.Parse(firstDocNum); j <= Int32.Parse(lastDocNum); j++)
                    {
                        result = MainActivity.fiscal.klen_Prepare_Document("0", j.ToString(), document_Type);
                        if (result["errorCode"] != "P") return;
                        else
                        {
                            if (StopReading) break;
                            if (!ReadLines_Loop_DeviceGroup_B())
                            {
                                lstTitles.Add((++id).ToString());
                                rej.Add(list.ToArray());
                                list.Clear();
                                continue;
                            }

                        }

                    }
                    this.Activity.RunOnUiThread(() =>
                    {
                        prgAction.Visibility = Android.Views.ViewStates.Invisible;
                    });
                }
            }
            catch (Exception ex)
            {
                this.Activity.RunOnUiThread(() =>
                {
                    MainActivity.ShowMessage(ex.Message, "Error");
                });
            }
        }

        public bool ReadLines_Loop_DeviceGroup_B()
        {
            string newStr = "";
            do
            {
                this.Activity.RunOnUiThread(() =>
                {
                    prgAction.Visibility = Android.Views.ViewStates.Visible;
                });

                // Read one line as text. Must be called multiple times to read the whole document
                var result = MainActivity.fiscal.klen_Get_TextRow("1");
                if (result["fAnswer"] == "F") return false;

                string[] textData = result["fTextRow"].Split(new string[] { "\r\n" }, StringSplitOptions.None);

                if (textData[0].Contains('^'))
                {

                    newStr = textData[0].Replace("^", " ");
                    // bold
                    list.Add(newStr + "\r\n");

                    //if (newStr.Contains("О б щ а   с у м а"))
                    //{
                    //    var tr = newStr.Replace("О б щ а   с у м а", "");
                    //    var trr = tr.Replace(" ", "");
                    //    if (trr != "") sum = trr;
                    //}
                }
                else
                    list.Add(textData[0] + "\r\n"); // Read one line as text.

                continue;

            }
            while (!StopReading);
            return true;
        }

        private void Calculate_Controls()
        {
            if (fView == null) return;
            fView.FindViewById<Button>(Resource.Id.btnStop).Enabled = false;
            fView.FindViewById<Button>(Resource.Id.btnReadEJDocs).Enabled = MainActivity.fiscal.device_Connected;
            fView.FindViewById<Button>(Resource.Id.btnPrintDocs).Enabled = MainActivity.fiscal.device_Connected;
            fView.FindViewById<Button>(Resource.Id.btnSelectStartDate).Enabled = !fView.FindViewById<CheckBox>(Resource.Id.chkByDocNum).Checked;
            fView.FindViewById<Button>(Resource.Id.btnSelectEndDate).Enabled = !fView.FindViewById<CheckBox>(Resource.Id.chkByDocNum).Checked;
            fView.FindViewById<Button>(Resource.Id.btnSelectEndTime).Enabled = !fView.FindViewById<CheckBox>(Resource.Id.chkByDocNum).Checked;
            fView.FindViewById<Button>(Resource.Id.btnSelectStartTime).Enabled = !fView.FindViewById<CheckBox>(Resource.Id.chkByDocNum).Checked;
            fView.FindViewById<Spinner>(Resource.Id.spinner).Enabled = true;
            fView.FindViewById<TextView>(Resource.Id.lblDocType).Enabled = true;
            fView.FindViewById<CheckBox>(Resource.Id.chkByDocNum).Enabled = true;
            fView.FindViewById<CheckBox>(Resource.Id.chkByZNum).Enabled = true;

            fView.FindViewById<TextView>(Resource.Id.lblFromZNum).Enabled = fView.FindViewById<CheckBox>(Resource.Id.chkByZNum).Checked;
            fView.FindViewById<TextView>(Resource.Id.lblToZNum).Enabled = fView.FindViewById<CheckBox>(Resource.Id.chkByZNum).Checked;
            fView.FindViewById<EditText>(Resource.Id.txtFromZNum).Enabled = fView.FindViewById<CheckBox>(Resource.Id.chkByZNum).Checked;
            fView.FindViewById<EditText>(Resource.Id.txtToZNum).Enabled = fView.FindViewById<CheckBox>(Resource.Id.chkByZNum).Checked;
            fView.FindViewById<TextView>(Resource.Id.lblFromNum).Enabled = fView.FindViewById<CheckBox>(Resource.Id.chkByDocNum).Checked;
            fView.FindViewById<TextView>(Resource.Id.lblToNum).Enabled = fView.FindViewById<CheckBox>(Resource.Id.chkByDocNum).Checked;
            fView.FindViewById<EditText>(Resource.Id.txtFromNum).Enabled = fView.FindViewById<CheckBox>(Resource.Id.chkByDocNum).Checked;
            fView.FindViewById<EditText>(Resource.Id.txtToNum).Enabled = fView.FindViewById<CheckBox>(Resource.Id.chkByDocNum).Checked;

        }
        private int id = 0;

        private void ParseInfoFromStructuredInfo(Dictionary<string, string> data)
        {

            try
            {
                if (data["datafield01"] == "U")
                {

                    list.Add("Структурирана информация за бона:\t\t" + "\r\n");
                    list.Add("УНП:\t\t" + data["datafield02"] + "\r\n");
                    list.Add("Номер на оператор:\t\t" + data["datafield03"] + "\r\n");
                    list.Add("Номер на касово място:\t\t" + data["datafield04"] + "\r\n");
                    if (data["datafield05"] == "0")
                        list.Add("Вид на бона:\t\t" + "фискален" + "\r\n");
                    if (data["datafield05"] == "1")
                        list.Add("Вид на бона:\t\t" + "фактура" + "\r\n");
                    if (data["datafield05"] == "2")
                        list.Add("Вид на бона:\t\t" + "сторно" + "\r\n");
                    if (data["datafield05"] == "3")
                        list.Add("Вид на бона:\t\t" + "кредитно известие" + "\r\n");
                    if (data["datafield05"] == "4")
                        list.Add("Вид на бона:\t\t" + "анулиран" + "\r\n");
                    list.Add("Глобален номер на документа:\t\t" + data["datafield06"] + "\r\n");
                    list.Add("\n");
                }

                if (data["datafield01"] == "V")
                {
                    // rtxEJ.SelectionFont = new Font(rtxEJ.Font, FontStyle.Bold);
                    list.Add("Структурирана информация за десетични знаци и данъчни ставки:\t" + "\r\n");
                    list.Add("Номер на записа с данъчни ставки във ФП:\t" + data["datafield02"] + "\r\n");
                    list.Add("Десетични знаци:\t" + data["datafield03"] + "\r\n");
                    list.Add("Десетична ставка 1 в проценти:\t" + data["datafield04"] + "\r\n");
                    list.Add("Десетична ставка 2 в проценти:\t" + data["datafield05"] + "\r\n");
                    list.Add("Десетична ставка 3 в проценти:\t" + data["datafield06"] + "\r\n");
                    list.Add("Десетична ставка 4 в проценти:\t" + data["datafield07"] + "\r\n");
                    list.Add("Десетична ставка 5 в проценти:\t" + data["datafield08"] + "\r\n");
                    list.Add("Десетична ставка 6 в проценти:\t" + data["datafield09"] + "\r\n");
                    list.Add("Десетична ставка 7 в проценти:\t" + data["datafield10"] + "\r\n");
                    list.Add("Десетична ставка 8 в проценти:\t" + data["datafield11"] + "\r\n");
                    list.Add("\n");
                }

                if (data["datafield01"] == "R")
                {
                    //rtxEJ.SelectionFont = new Font(rtxEJ.Font, FontStyle.Bold);
                    list.Add("Структурирана информация за продажба или корекция:\t" + "\r\n");
                    list.Add("Данъчна група:\t" + data["datafield02"] + "\r\n");
                    list.Add("Данъчна ставка в проценти:\t" + data["datafield03"] + "\r\n");
                    list.Add("Единична цена:\t" + data["datafield04"] + "\r\n");
                    list.Add("Количество:\t" + data["datafield05"] + "\r\n");
                    list.Add("Отстъпка/надбавка:\t" + data["datafield06"] + "\r\n");
                    list.Add("Цена:\t" + data["datafield07"] + "\r\n");
                    if (data["datafield08"].Contains("\t"))
                    {
                        var result = data["datafield08"].Split('\t');
                        list.Add("Име на продадената стока:\t" + result[0] + "\r\n");
                        list.Add("Име на продадената стока (втори ред):\t" + result[1] + "\r\n");
                    }
                    else list.Add("Име на продадената стока:\t" + data["datafield08"] + "\r\n");
                    list.Add("\n");
                }

                if (data["datafield01"] == "M")
                {
                    // rtxEJ.SelectionFont = new Font(rtxEJ.Font, FontStyle.Bold);
                    list.Add("Структурирана информация групова отстъпка/надбавка:\t" + "\r\n");
                    list.Add("Отстъпка/надбавка:\t" + data["datafield02"] + "\r\n");
                    list.Add("Процент на отстъпката/надбавката:\t" + data["datafield03"] + "\r\n");
                    list.Add("Междинна сума след операцията:\t" + data["datafield04"] + "\r\n");
                    list.Add("\n");
                }

                if (data["datafield01"] == "T")
                {
                    // rtxEJ.SelectionFont = new Font(rtxEJ.Font, FontStyle.Bold);
                    list.Add("Структурирана информация за натрупаните суми в бона:\t" + "\r\n");
                    list.Add("Брой отстъпки:\t" + data["datafield02"] + "\r\n");
                    list.Add("Сума от отстъпки:\t" + data["datafield03"] + "\r\n");
                    list.Add("Брой надбавки:\t" + data["datafield04"] + "\r\n");
                    list.Add("Сума от надбавки:\t" + data["datafield05"] + "\r\n");
                    list.Add("Брой от корекции:\t" + data["datafield06"] + "\r\n");
                    list.Add("Сума от корекции:\t" + data["datafield07"] + "\r\n");
                    list.Add("Брой продажби:\t" + data["datafield08"] + "\r\n");
                    list.Add("Обща сума за бона:\t" + data["datafield09"] + "\r\n");
                    list.Add("Сума по данъчна група 1:\t" + data["datafield10"] + "\r\n");
                    list.Add("Сума по данъчна група 2:\t" + data["datafield11"] + "\r\n");
                    list.Add("Сума по данъчна група 3:\t" + data["datafield12"] + "\r\n");
                    list.Add("Сума по данъчна група 4:\t" + data["datafield13"] + "\r\n");
                    list.Add("Сума по данъчна група 5:\t" + data["datafield14"] + "\r\n");
                    list.Add("Сума по данъчна група 6:\t" + data["datafield15"] + "\r\n");
                    list.Add("Сума по данъчна група 7:\t" + data["datafield16"] + "\r\n");
                    list.Add("Сума по данъчна група 8:\t" + data["datafield17"] + "\r\n");
                    list.Add("\n");
                }

                if (data["datafield01"] == "P")
                {
                    //rtxEJ.SelectionFont = new Font(rtxEJ.Font, FontStyle.Bold);
                    list.Add("Структурирана информация за платените суми:\t" + "\r\n");
                    list.Add("Платено в брой:\t" + data["datafield02"] + "\r\n");
                    list.Add("Платено с чек:\t" + data["datafield03"] + "\r\n");
                    list.Add("Платено с карта:\t" + data["datafield04"] + "\r\n");
                    list.Add("Платено с кредитна карта:\t" + data["datafield05"] + "\r\n");
                    list.Add("Допълнително плащане 1:\t" + data["datafield06"] + "\r\n");
                    list.Add("Допълнително плащане 2:\t" + data["datafield07"] + "\r\n");
                    list.Add("Допълнително плащане 3:\t" + data["datafield08"] + "\r\n");
                    list.Add("Допълнително плащане 4:\t" + data["datafield09"] + "\r\n");
                    list.Add("Допълнително плащане 5:\t" + data["datafield10"] + "\r\n");
                    list.Add("Допълнително плащане 6:\t" + data["datafield11"] + "\r\n");
                    list.Add("Допълнително плащане 7:\t" + data["datafield12"] + "\r\n");
                    list.Add("Допълнително плащане 8:\t" + data["datafield13"] + "\r\n");
                    list.Add("Допълнително плащане 9:\t" + data["datafield14"] + "\r\n");
                    list.Add("Допълнително плащане 10:\t" + data["datafield15"] + "\r\n");
                    list.Add("Допълнително плащане 11:\t" + data["datafield16"] + "\r\n");
                    list.Add("\n");
                }

                if (data["datafield01"] == "S")
                {
                    //rtxEJ.SelectionFont = new Font(rtxEJ.Font, FontStyle.Bold);
                    list.Add("Структурирана информация за сторниран бон:\t" + "\r\n");
                    if (data["datafield02"] == "0")
                        list.Add("Тип на сторното:\t" + "операторска грешка" + "\r\n");
                    if (data["datafield02"] == "1")
                        list.Add("Тип на сторното:\t" + "ръщане/рекламация" + "\r\n");
                    if (data["datafield02"] == "2")
                        list.Add("Тип на сторното:\t" + "намаление на данъчна основа" + "\r\n");
                    list.Add("Номер на сторнирания документ:\t" + data["datafield03"] + "\r\n");
                    list.Add("Дата и час на сторнирания документ:\t" + data["datafield04"] + "\r\n");
                    list.Add("Номер на фискалната памет за сторнирания документ:\t" + data["datafield05"] + "\r\n");
                    list.Add("Уникален номер на продажба на сторнирания документ:\t" + data["datafield06"] + "\r\n");
                    list.Add("Номер на фактура:\t" + data["datafield07"] + "\r\n");
                    list.Add("\n");
                }

                if (data["datafield01"] == "I")
                {
                    //rtxEJ.SelectionFont = new Font(rtxEJ.Font, FontStyle.Bold);
                    list.Add("Структурирана информация за фактура:\t" + "\r\n");
                    list.Add("Номер на фактура:\t" + data["datafield02"] + "\r\n");
                    list.Add("ПИН:\t" + data["datafield03"] + "\r\n");
                    if (data["datafield04"] == "0")
                        list.Add("Вид на ПИН:\t" + "БУЛСТАТ" + "\r\n");
                    if (data["datafield04"] == "1")
                        list.Add("Вид на ПИН:\t" + "ЕГН" + "\r\n");
                    if (data["datafield04"] == "2")
                        list.Add("Вид на ПИН:\t" + "Личен номер" + "\r\n");
                    if (data["datafield04"] == "3")
                        list.Add("Вид на ПИН:\t" + "Служебен номер" + "\r\n");
                    list.Add("\n");
                }
                if (data["datafield01"] == "D")
                {
                    //rtxEJ.SelectionFont = new Font(rtxEJ.Font, FontStyle.Bold);
                    list.Add("Дата и час на започване и на завършване на бона:\t" + "\r\n");
                    list.Add("Начална дата и час:\t" + data["datafield02"] + "\r\n");
                    list.Add("Крайна дата и час:\t" + data["datafield03"] + "\r\n");
                    list.Add("\n");
                }
                if (data["datafield01"] == "Z")
                {
                    //rtxEJ.SelectionFont = new Font(rtxEJ.Font, FontStyle.Bold);
                    list.Add("Дневен отчет:\t\t" + "\r\n");
                    list.Add("Номер на дневния отчет:\t\t" + data["datafield02"] + "\r\n");
                    list.Add("Номер на документ:\t\t" + data["datafield03"] + "\r\n");
                    list.Add("Номер на последен фискален документ:\t\t" + data["datafield04"] + "\r\n");
                    list.Add("Дата и час във формат:\t\t" + data["datafield05"] + "\r\n");
                    list.Add("Обща сума от продажби за деня:\t\t" + data["datafield06"] + "\r\n");
                    list.Add("Обща сума от сторно бонове:\t\t" + data["datafield07"] + "\r\n");
                    list.Add("Касова наличност:\t\t" + data["datafield08"] + "\r\n");
                    list.Add("\n");
                }
                if (data["datafield01"] == "Q")
                {
                    // rtxEJ.SelectionFont = new Font(rtxEJ.Font, FontStyle.Bold);
                    list.Add("Служебно въведени / изведени:\t" + "\r\n");
                    list.Add("Номер на документ:\t" + data["datafield02"] + "\r\n");
                    list.Add("Дата и час:\t" + data["datafield03"] + "\r\n");
                    list.Add("Служебно въведена / изведена сума:\t" + data["datafield04"] + "\r\n");
                    list.Add("Касова наличност:\t" + data["datafield05"] + "\r\n");
                    list.Add("\n");
                }
            }
            catch (Exception)
            {
                throw;
            }
        }

        private void ParseInfoFromStrInfo_ClassV(string data)
        {
            var dataV = data.Split('\t');
            // rtxEJ.SelectionFont = new Font(rtxEJ.Font, FontStyle.Bold);
            list.Add("Структурирана информация клас V:\t" + "\r\n");
            list.Add("Идентификационен номер на ФУ:\t" + dataV[0] + "\r\n");
            list.Add("Вид на фискалния бон:\t" + dataV[1] + "\r\n");
            list.Add("Номер на фискалния бон:\t" + dataV[2] + "\r\n");
            list.Add("Уникален номер на продажбата (УНП):\t" + dataV[3] + "\r\n");
            list.Add("Стока/услуга – наименование:\t" + dataV[4] + "\r\n");
            list.Add("Стока/услуга – единична цена:\t" + dataV[5] + "\r\n");
            list.Add("Стока/услуга – количество:\t" + dataV[6] + "\r\n");
            list.Add("Стока/услуга – стойност:\t" + dataV[7] + "\r\n");
            list.Add("Обща сума:\t" + dataV[8] + "\r\n");
            list.Add("Номер на фактура/кредитно известие:\t" + dataV[9] + "\r\n");
            list.Add("ЕИК на получател:\t" + dataV[10] + "\r\n");
            list.Add("Номер на сторниран ФБ:\t" + dataV[11] + "\r\n");
            list.Add("Номер на сторнирана фактура:\t" + dataV[12] + "\r\n");
            list.Add("Причина за издаване:\t" + dataV[13] + "\r\n");
        }

        
        public bool ReadLines_Loop()
        {
            //bool f = false;
            do
            {
                this.Activity.RunOnUiThread(() =>
                {
                    prgAction.Visibility = Android.Views.ViewStates.Visible;
                });

                // Read one line as text. Must be called multiple times to read the whole document
                var result = MainActivity.fiscal.klen_Get_NextTextRow("N");

                if (result["fAnswer"] == "F")
                {
                    this.Activity.RunOnUiThread(() =>
                    {

                        prgAction.Visibility = Android.Views.ViewStates.Invisible;
                    });
                    break; // "F" if there is no data or all data is already written.
                }

                else if (result["fAnswer"] == "*")
                {
                    this.Activity.RunOnUiThread(() =>
                    {
                        lstReceiptsContainer.Adapter = new ArrayAdapter(MainActivity.GetInstance(), Resource.Layout.RecList_Item, lstTitles.ToArray());

                    });
                    lstTitles.Add((++id).ToString());
                    rej.Add(list.ToArray());
                    list.Clear();
                }
                else
                {
                    list.Add(result["fRow"] + "\r\n");
                    continue;
                }

            }
            while (!StopReading);

            return true;
        }

        private bool Check_DateTime(string stD, string endD, string stT, string endT)
        {
            SimpleDateFormat formatStart = new SimpleDateFormat("ddMMyy");
            SimpleDateFormat formatEnd = new SimpleDateFormat("ddMMyy");
            SimpleDateFormat formatStartTime = new SimpleDateFormat("HHmmss");
            SimpleDateFormat formatEndTime = new SimpleDateFormat("HHmmss");

            Date dateSt = formatStart.Parse(stD);
            Date dateEnd = formatEnd.Parse(endD);
            Date timeSt = formatStartTime.Parse(stT);
            Date timeEnd = formatEndTime.Parse(endT);
            if (dateSt.CompareTo(dateEnd) > 0)
            {
                MainActivity.ShowMessage("Starting date is greater than ending one!", "Warning");
                return false;
            }
            else
            {
                if (dateSt.CompareTo(dateEnd) == 0)
                {
                    if (timeSt.CompareTo(timeEnd) > 0)
                    {
                        MainActivity.ShowMessage("Starting time is greater than ending one!", "Warning");
                        return false;
                    }
                }
            }
            return true;
        }

        private string Calculate_DocumentType()
        {
            switch (fView.FindViewById<Spinner>(Resource.Id.spinner).SelectedItemPosition)
            {
                case 0: document_Type = "0"; break;     //Всички.
                case 1: document_Type = "1"; break;     //Фискални бонове (всички фискални бонове, продажба, сторно, фактура, сторно фактура (кр.
                                                        //известие), дневен финансов отчет(Z отчет)).
                case 2: document_Type = "2"; break;     //Дневен Z отчет.
                case 3: document_Type = "3"; break;     //Сл. въведени/изведени.
                case 4: document_Type = "4"; break;     //Дневен X отчет.
                case 5: document_Type = "5"; break;     //Служебни бонове (всички без изброените в опция 1).
                case 6: document_Type = "6"; break;     //Фактура.
                case 7: document_Type = "7"; break;     //Сторно фискални бонове.
                case 8: document_Type = "8"; break;     //Сторно фактура (кр. известие).

            }
            return document_Type;
        }

        private void BtnPrintDocs_Click(object sender, EventArgs e)
        {
            string fromDate = "", toDate = "", fromTime = "", toTime = "", fromDT = "", ToDT = "";
            uint i = 0;
            if (MainActivity.fiscal == null) return;
            if (!MainActivity.fiscal.device_Connected) return;
            if (fView == null) return;
            StopReading = false;
            Calculate_DocumentType();
            ManageEJControls(false);
            fView.FindViewById<Button>(Resource.Id.btnStop).Enabled = false;
            ExecuteFiscalCode(() =>
            {

                prgAction.Visibility = Android.Views.ViewStates.Visible;

                if (fView.FindViewById<CheckBox>(Resource.Id.chkByDocNum).Checked)
                {
                    if (!checkDocumentNumsBoxes()) return;
                    if (fView.FindViewById<EditText>(Resource.Id.txtToZNum).Enabled)
                    {
                        if (fView.FindViewById<EditText>(Resource.Id.txtFromZNum).Text != "")
                        {
                            
                            //string txtFromNum = fView.FindViewById<EditText>(Resource.Id.txtFromNum).Text;
                            string txtToZ = fView.FindViewById<EditText>(Resource.Id.txtToZNum).Text;
                            string txtFromZ = fView.FindViewById<EditText>(Resource.Id.txtFromZNum).Text;
                            // return;
                            ExecuteFiscalCodeWithThread(() =>
                            {
                                for (i = uint.Parse(txtFromZ); i <= uint.Parse(txtToZ); i++)
                                {
                                    var result = MainActivity.fiscal.klen_FindRange_ByZReports("Z", document_Type, txtFromZ, txtToZ);
                                    if (result["errorCode"] != "P") return;
                                    else
                                    {
                                        if (result["firstDocumentNumber"] == "" && result["lastDocumentNumber"] == "") break;
                                        for (i = uint.Parse(result["firstDocumentNumber"]); i <= Int32.Parse(result["lastDocumentNumber"]); i++)
                                        {
                                            var res = MainActivity.fiscal.klen_Print_Document("3", i.ToString(), document_Type);
                                            if (res["errorCode"] != "P") return;
                                        }
                                    }
                                }
                            });
                        }

                    }
                    else
                    {
                        string txtToNum = fView.FindViewById<EditText>(Resource.Id.txtToNum).Text;
                        string txtFromNum = fView.FindViewById<EditText>(Resource.Id.txtFromNum).Text;
                        ExecuteFiscalCodeWithThread(() =>
                        {
                            for (i = uint.Parse(txtFromNum); i <= uint.Parse(txtToNum); i++)
                            {
                                var res = MainActivity.fiscal.klen_Print_Document("3", i.ToString(), document_Type);
                                if (res["errorCode"] != "P") return;
                            }
                        });
                    }
                }
                else
                {


                    fromDate = String.Format("{0:ddMMyy}", fView.FindViewById<EditText>(Resource.Id.txtStartDate).Text); // start date in format "ddMMyy"
                    toDate = String.Format("{0:ddMMyy}", fView.FindViewById<EditText>(Resource.Id.txtEndDate).Text);// end date in format "ddMMyy"
                    fromTime = String.Format("{0:HHmmss}", fView.FindViewById<EditText>(Resource.Id.txtStartTime).Text); // start time in format "HHmmss"
                    toTime = String.Format("{0:HHmmss}", fView.FindViewById<EditText>(Resource.Id.txtEndTime).Text);// end time in format "HHmmss"
                    fromDT = fromDate + fromTime;
                    ToDT = toDate + toTime;
                    Calculate_DocumentType();

                    if (!Check_DateTime(fromDate, toDate, fromTime, toTime)) return;
                   
                    ExecuteFiscalCodeWithThread(() =>
                    {
                        var result = MainActivity.fiscal.klen_FindRange_ByDateTime("D", document_Type, fromDT, ToDT);
                        if (result["errorCode"] != "P") return;
                        else
                        {
                            if (result["firstDocumentNumber"] == "" && result["lastDocumentNumber"] == "") return;
                            for (i = uint.Parse(result["firstDocumentNumber"]); i <= uint.Parse(result["lastDocumentNumber"]); i++)
                            {
                                result = MainActivity.fiscal.klen_Print_Document("3", i.ToString(), document_Type);
                                if (result["errorCode"] != "P") break;
                            }
                        }
                    });
                }
            });
        }
        private void BtnStop_Click(object sender, EventArgs e)
        {
            StopReading = true;
            ManageEJControls(true);
            Calculate_Controls();
        }

        private void ReadStrInfoByZNums_Class_B(string fromZ, string toZ)
        {
            int i;

            var result = MainActivity.fiscal.klen_FindRange_ByZReports("Z", "1", fromZ, toZ);
            if (result["errorCode"] == "F") return;

            for (i = Int32.Parse(result["startNumber"]); i <= Int32.Parse(result["endNumber"]); i++)
            {
                var result1 = MainActivity.fiscal.klen_Prepare_DocumentInRange("0", i.ToString(), "1", result["endNumber"]);
                if (result1["errorCode"] == "F") continue;
                if (i.ToString() != result1["documentNumber"])
                {
                    i = Int32.Parse(result1["documentNumber"]) - 1;
                    continue;
                }
                if (StopReading) return;
                while (true)
                {
                    var result2 = MainActivity.fiscal.klen_Get_Data("2");
                    if (result2["fAnswer"] == "F")
                    {
                        lstTitles.Add(i.ToString());
                        this.Activity.RunOnUiThread(() =>
                        {
                            lstReceiptsContainer.Adapter = new ArrayAdapter(MainActivity.GetInstance(), Resource.Layout.RecList_Item, lstTitles.ToArray());

                        });
                        rej.Add(list.ToArray());
                        list.Clear();
                        break;
                    }
                    else
                    {
                        if (StopReading) return;
                        if (result2["fData"].Length == 0)
                        {
                            this.Activity.RunOnUiThread(() =>
                            {
                                MainActivity.ShowMessage("There no data into a last answer list.", "Warning");
                            });
                            return;
                        }
                        else
                        {
                            byte[] data = System.Convert.FromBase64String(result2["fData"]);
                            var c = new StructuredInfoRegister_DeviceGroup_B(data);
                            ParseInfoFromStructure_B(c.Type, data);
                        }

                    }
                }

                list.Add("\r\n");
                if (StopReading) return;

            }
        }

        private void ReadStrInfoByNums_Class_B(string fromNum, string toNum)
        {
            int i;
            try
            {
                for (i = Int32.Parse(fromNum); i <= Int32.Parse(toNum); i++)
                {
                    var result = MainActivity.fiscal.klen_Prepare_Document("0", i.ToString(), "1");
                    if (result["errorCode"] == "F") continue;
                    if (i.ToString() != result["documentNumber"])
                    {
                        i = Int32.Parse(result["documentNumber"]) - 1;
                        continue;
                    }
                    if (StopReading) return;
                    while (true)
                    {
                        var result1 = MainActivity.fiscal.klen_Get_Data("2");
                        if (result1["fAnswer"] == "F")
                        {
                            lstTitles.Add(i.ToString());
                            this.Activity.RunOnUiThread(() =>
                            {
                                lstReceiptsContainer.Adapter = new ArrayAdapter(MainActivity.GetInstance(), Resource.Layout.RecList_Item, lstTitles.ToArray());

                            });
                            rej.Add(list.ToArray());
                            list.Clear();
                            break;
                        }

                        else
                        {
                            if (StopReading) return;
                            if (result1["fData"].Length == 0)
                            {
                                this.Activity.RunOnUiThread(() =>
                                {
                                    MainActivity.ShowMessage("There no data into a last answer list.", "Warning");
                                });
                                return;
                            }
                            else
                            {

                                byte[] data = System.Convert.FromBase64String(result1["fData"]);
                                var c = new StructuredInfoRegister_DeviceGroup_B(data);
                                ParseInfoFromStructure_B(c.Type, data);

                            }

                        }
                    }


                    list.Add("\r\n");
                    if (StopReading) return;

                }
            }
            finally
            {
                //
            }

        }

        private void ReadStrInfoByDates_Class_B(string fromDT, string toDT)
        {
            int i;

            var result = MainActivity.fiscal.klen_FindRange_ByDateTime("D", "1", fromDT, toDT);
            if (result["errorCode"] == "F") return;

            for (i = Int32.Parse(result["firstDocumentNumber"]); i <= Int32.Parse(result["lastDocumentNumber"]); i++)
            {
                var result1 = MainActivity.fiscal.klen_Prepare_DocumentInRange("0", i.ToString(), "1", result["lastDocumentNumber"]);
                if (result1["errorCode"] == "F") continue;
                if (i.ToString() != result1["documentNumber"])
                {
                    i = Int32.Parse(result1["documentNumber"]) - 1;
                    continue;
                }
                if (StopReading) return;
                while (true)
                {
                    var result2 = MainActivity.fiscal.klen_Get_Data("2");
                    if (result2["fAnswer"] == "F")
                    {
                        lstTitles.Add(i.ToString());
                        this.Activity.RunOnUiThread(() =>
                        {
                            lstReceiptsContainer.Adapter = new ArrayAdapter(MainActivity.GetInstance(), Resource.Layout.RecList_Item, lstTitles.ToArray());

                        });
                        rej.Add(list.ToArray());
                        list.Clear();
                        break;
                    }
                    else
                    {
                        if (result2["fData"].Length == 0)
                        {
                            this.Activity.RunOnUiThread(() =>
                            {
                                MainActivity.ShowMessage("There no data into a last answer list.", "Warning");
                            });
                            return;
                        }
                        else
                        {
                            byte[] data = System.Convert.FromBase64String(result2["fData"]);
                            var c = new StructuredInfoRegister_DeviceGroup_B(data);
                            ParseInfoFromStructure_B(c.Type, data);
                        }

                        if (StopReading) return;

                    }
                }
                list.Add("\r\n");
                if (StopReading) return;

            }
        }

        private void ParseInfoFromStructure_B(StructuredInfoRegister_DeviceGroup_B.tagRClass type, byte[] data)
        {
            var c = new StructuredInfoRegister_DeviceGroup_B(data);
            switch (type)
            {
                case StructuredInfoRegister_DeviceGroup_B.tagRClass.UNKNOWN:
                    {
                        break;
                    }
                case StructuredInfoRegister_DeviceGroup_B.tagRClass.PLUSELL:
                case StructuredInfoRegister_DeviceGroup_B.tagRClass.DPxSELL:
                case StructuredInfoRegister_DeviceGroup_B.tagRClass.VD_PLUSELL:
                case StructuredInfoRegister_DeviceGroup_B.tagRClass.VD_DPxSELL:
                    {
                        var sell = c.CmdSell;
                       
                        list.Add("Sell:\t" + "\r\n");
                        list.Add("Флаг за void операция:\t" + sell.cancel.ToString() + "\r\n");
                        list.Add("PLU номер:\t" + sell.fMyPluDB.ToString() + "\r\n");
                        list.Add("Данъчна група:\t" + sell.vat + "\r\n");
                        list.Add("Единична цена:\t" + sell.prc.ToString() + "\r\n");
                        list.Add("Сума:\t" + sell.suma.ToString() + "\r\n"); // Сума = qty*prc   
                        list.Add("Номенклатурен код:\t" + sell.icode.ToString() + "\r\n");
                        list.Add("Баркод:\t" + sell.bcode.ToString() + "\r\n");
                        list.Add("Продадено количество:\t" + sell.qty.ToString() + "\r\n");
                        list.Add("Име:\t" + GetStringFromCharArr(sell.name) + "\r\n");
                        list.Add("Тип отстъпка/надбавка:\t" + sell.typeIncDec.ToString() + "\r\n");
                        list.Add("Номер на департамент:\t" + sell.dep.ToString() + "\r\n");
                        list.Add("Процент или стойност:\t" + sell.sIncDec.ToString() + "\r\n");
                        list.Add("Номер на стокова група:\t" + sell.grp.ToString() + "\r\n");
                        list.Add("Разширено име:\t" + GetStringFromCharArr(sell.ext_name) + "\r\n");
                        list.Add("Контролна сума:\t" + sell.checksum.ToString() + "\r\n");
                        list.Add("\r\n");
                        break;
                    }
                case StructuredInfoRegister_DeviceGroup_B.tagRClass.PAYMENT:
                    {
                        var pay = c.CmdPay;
                        
                        list.Add("Payment:\t" + "\r\n");
                        list.Add("Подтип:\t" + pay.subtype.ToString() + "\r\n");
                        list.Add("Име на валута:\t" + GetStringFromByteArr(pay.name_currency) + "\r\n");
                        list.Add("Въведена сума:\t" + pay.sInput.ToString() + "\r\n");
                        list.Add("Ресто:\t" + pay.sResto.ToString() + "\r\n");
                        list.Add("Ресто в алтернативна валута:\t" + pay.sRestoForeign.ToString() + "\r\n");
                        list.Add("Сума подадена от клиента в алт.валута:\t" + pay.sPYN.ToString() + "\r\n");
                        list.Add("Сума преизчислена в осн.валута" + pay.sPYosnov.ToString() + "\r\n");
                        list.Add("Сума преизчислена спореeд курса:\t" + pay.sTLneosn.ToString() + "\r\n");
                        list.Add("Курс на основна -> алт.валута:\t" + pay.sExchRate.ToString() + "\r\n");
                        list.Add("Име на плащането:\t" + GetStringFromCharArr(pay.pay_name) + "\r\n");
                        list.Add("Контролна сума:\t" + pay.checksum.ToString() + "\r\n");
                        break;
                    }
                case StructuredInfoRegister_DeviceGroup_B.tagRClass.OTS_NDB:
                case StructuredInfoRegister_DeviceGroup_B.tagRClass.VD_OTS_NDB:
                    {
                        var discSurc = c.CmdPerc;
                        
                        list.Add("Discount/Surcharge:\t" + "\r\n");
                        list.Add("Подтип:\t" + discSurc.subtype.ToString() + "\r\n");
                        list.Add("Флаг за void операция:\t" + discSurc.cancel.ToString() + "\r\n");
                        list.Add("Флаг за операция над STL:\t" + discSurc.flagSTL.ToString() + "\r\n");
                        list.Add("Данъчна група:\t" + discSurc.nVAT.ToString() + "\r\n");
                        list.Add("Департамент:\t" + discSurc.dep.ToString() + "\r\n");
                        list.Add("Номер на стокова група:\t" + discSurc.grp.ToString() + "\r\n");
                        list.Add("Сума на транзакцията:\t" + discSurc.sSuma.ToString() + "\r\n");
                        list.Add("Обща сума по дан. групи преди %STL:\t" + discSurc.sSTL.ToString() + "\r\n");
                        list.Add("Сума по дан.групи преди %STL:\t" + discSurc.sVAT.ToString() + "\r\n");
                        list.Add("Стойност на отстъпка/надбавка:\t" + discSurc.percIncDec.ToString() + "\r\n");
                        list.Add("Контролна сума:\t" + discSurc.checksum.ToString() + "\r\n" + "\r\n");
                        break;
                    }
                case StructuredInfoRegister_DeviceGroup_B.tagRClass.RA_PO:
                    {
                        var rapo = c.CmdRapo;
                        
                        list.Add("Rapo:\t" + "\r\n");
                        list.Add("Подтип:\t" + rapo.subtype.ToString() + "\r\n");
                        list.Add("Име на валута:\t" + GetStringFromByteArr(rapo.name_currency) + "\r\n");
                        list.Add("Въведена сума:\t" + rapo.sInput.ToString() + "\r\n");
                        list.Add("Курс на основна -> алт.валута:\t" + rapo.sExchRate.ToString() + "\r\n");
                        list.Add("Контролна сума:\t" + rapo.checksum.ToString() + "\r\n" + "\r\n");
                        break;
                    }

                case StructuredInfoRegister_DeviceGroup_B.tagRClass.QTYSET:
                    {
                        //не се използва
                        break;
                    }
                case StructuredInfoRegister_DeviceGroup_B.tagRClass.PRCSET:
                    {
                        //не се използва
                        break;
                    }

                case StructuredInfoRegister_DeviceGroup_B.tagRClass.ABONAT:
                    {
                        //не се използва
                        break;
                    }
                case StructuredInfoRegister_DeviceGroup_B.tagRClass.BEGPAY:
                    {
                        var total = c.CmdTotal;
                        
                        list.Add("Total:\t" + "\r\n");
                        list.Add("Име на валута:\t" + GetStringFromByteArr(total.name_currency) + "\r\n");
                        list.Add("Обща сума:\t" + total.sSTL.ToString() + "\r\n");
                        list.Add("Данъчна група:\t" + total.sVAT.ToString() + "\r\n");
                        list.Add("Курс на основна -> алт.валута:\t" + total.sExchRate.ToString() + "\r\n");
                        list.Add("Контролна сума:\t" + total.checksum.ToString() + "\r\n" + "\r\n");
                        break;
                    }
                case StructuredInfoRegister_DeviceGroup_B.tagRClass.BOTTLE:
                    {
                        //не се използва
                        break;
                    }
                case StructuredInfoRegister_DeviceGroup_B.tagRClass.VD_BOTTLE:
                    {
                        //не се използва
                        break;
                    }
                case StructuredInfoRegister_DeviceGroup_B.tagRClass.COUPON:
                    {
                        //не се използва
                        break;
                    }
                case StructuredInfoRegister_DeviceGroup_B.tagRClass.TICKET:
                    {
                        //не се използва
                        break;
                    }
                case StructuredInfoRegister_DeviceGroup_B.tagRClass.ALL_VOID:
                    {
                        var allVoid = c.CmdAllVoid;
                        
                        list.Add("All void:\t" + "\r\n");
                        list.Add("Брой корекции в дн. отчет:\t" + allVoid.nCorrections.ToString() + "\r\n");
                        list.Add("Обща сума:\t" + allVoid.sTL.ToString() + "\r\n");
                        list.Add("Данъчна група:\t" + allVoid.sVAT.ToString() + "\r\n");
                        list.Add("Контролна сума:\t" + allVoid.checksum.ToString() + "\r\n" + "\r\n");
                        break;
                    }
                case StructuredInfoRegister_DeviceGroup_B.tagRClass.REPORTS:
                    {
                        //не се използва
                        break;
                    }
                case StructuredInfoRegister_DeviceGroup_B.tagRClass.TEXT_LINE:
                    {
                        var textLine = c.CmdTextLine;
                        
                        list.Add("Text line:\t" + "\r\n");
                        list.Add("Текст:\t" + GetStringFromByteArr(textLine.text) + "\r\n");
                        list.Add("Контролна сума:\t" + textLine.checksum.ToString() + "\r\n" + "\r\n");
                        break;
                    }
                case StructuredInfoRegister_DeviceGroup_B.tagRClass.OPEN_BON:
                    {
                        var open = c.CmdOpen;
                        
                        list.Add("Open receipt:\t" + "\r\n");
                        list.Add("Дата и час:\t" + StructuredInfoRegister_DeviceGroup_B.DateToString(open.strDateTime) + "\r\n");
                        list.Add("Номер на оператор:\t" + open.nOperator.ToString() + "\r\n");
                        list.Add("Номер на бон:\t" + open.nBon.ToString() + "\r\n");
                        list.Add("Флагове:\t" + open.flags.ToString() + "\r\n");
                        list.Add("Номер на фактура:\t" + open.invN.ToString() + "\r\n");
                        list.Add("Номер на фактура, към която е сторното:\t" + open.strToInvoice.ToString() + "\r\n");
                        list.Add("Номер на бона, по който е сторното:\t" + open.strNumberDoc.ToString() + "\r\n");
                        list.Add("Тип на бона:\t" + open.klenType.ToString() + "\r\n");
                        list.Add("Тип на сторно операция:\t" + open.strType.ToString() + "\r\n");//      Тип на сторно операцията: 0 - операторска грешка, 1 - връщане/рекламация
                        list.Add("Номер на фискалната памет на бона:\t" + GetStringFromCharArr(open.strFMnumber) + "\r\n");
                        list.Add("Уникален номер на продажба:\t" + GetStringFromCharArr(open.nSale) + "\r\n");
                        list.Add("Позиция на десетичната точка:\t" + open.dp.ToString() + "\r\n");
                        list.Add("Номер на устройството:\t" + GetStringFromCharArr(open.deviceID) + "\r\n");
                        list.Add("Контролна сума:\t" + open.checksum.ToString() + "\r\n" + "\r\n");
                        break;
                    }
                case StructuredInfoRegister_DeviceGroup_B.tagRClass.CLOSE_BON:
                    {
                        //не се използва
                        break;
                    }
                case StructuredInfoRegister_DeviceGroup_B.tagRClass.HEADER_FOOTER:
                    {
                        var headerFooter = c.CmdHeaderFooter;
                        list.Add("Header and footer:\t" + "\r\n");
                        list.Add("Подтип:\t" + headerFooter.subtype.ToString() + "\r\n");
                        list.Add("Номер на ред:\t" + headerFooter.nLine.ToString() + "\r\n");
                        list.Add("Текст за отпечатване:\t" + GetStringFromCharArr(headerFooter.text) + "\r\n");
                        list.Add("Контролна сума:\t" + headerFooter.checksum.ToString() + "\r\n" + "\r\n");
                        break;
                    }
                case StructuredInfoRegister_DeviceGroup_B.tagRClass.PINPAD_INFO:
                    {
                        //не се използва
                        break;
                    }
                case StructuredInfoRegister_DeviceGroup_B.tagRClass.INTERNAL:
                    {
                        //не се използва
                        break;
                    }
            }

        }

        static Encoding PLEncoding = ASCIIEncoding.GetEncoding(1251);
        public static string GetStringFromByteArr(byte[] data)
        {
            int end = 0;
            for (end = 0; end < data.Length; end++)
                if (data[end] == 0)
                    break;
            return PLEncoding.GetString(data, 0, end);
        }

        public static string GetStringFromCharArr(char[] full)
        {
            for (int i = 0; i < full.Length; i++)
            {
                if (full[i] == 0)
                    return new string(full, 0, i).Trim();
            }
            return new string(full).Trim();
        }

        private void BtnReadStructured_Click(object sender, EventArgs e)
        {
            string fromDate = "", toDate = "", fromTime = "", toTime = "", fromDT = "", ToDT = "";
            uint i = 0;
            if (MainActivity.fiscal == null) return;
            if (!MainActivity.fiscal.device_Connected) return;
            if (fView == null) return;
            StopReading = false;
            Calculate_DocumentType();
            rej.Clear();
            list.Clear();
            lstTitles.Clear();
            ManageEJControls(false);
            fView.FindViewById<Button>(Resource.Id.btnStop).Enabled = false;
            string txtToZ = fView.FindViewById<EditText>(Resource.Id.txtToZNum).Text;
            string txtFromZ = fView.FindViewById<EditText>(Resource.Id.txtFromZNum).Text;
            ExecuteFiscalCode(() =>
            {

                prgAction.Visibility = Android.Views.ViewStates.Visible;

                if (fView.FindViewById<CheckBox>(Resource.Id.chkByDocNum).Checked)
                {
                    if (!checkDocumentNumsBoxes()) return;

                    string txtToNum = fView.FindViewById<EditText>(Resource.Id.txtToNum).Text;
                    string txtFromNum = fView.FindViewById<EditText>(Resource.Id.txtFromNum).Text;

                    // return;
                    ExecuteFiscalCodeWithThread(() =>
                            {
                                ReadStrInfoByNums_Class_B(txtFromNum, txtToNum); 
                            });


                }
                else if (txtFromZ!= "" && fView.FindViewById<CheckBox>(Resource.Id.chkByZNum).Checked)
                {
                    
                    if (!checkDocumentNumsBoxes()) return;
                    ExecuteFiscalCodeWithThread(() =>
                    {
                        ReadStrInfoByZNums_Class_B(txtFromZ, txtToZ);
                    });
                }
                else
                {
                    fromDate = String.Format("{0:ddMMyy}", fView.FindViewById<EditText>(Resource.Id.txtStartDate).Text); // start date in format "ddMMyy"
                    toDate = String.Format("{0:ddMMyy}", fView.FindViewById<EditText>(Resource.Id.txtEndDate).Text);// end date in format "ddMMyy"
                    fromTime = String.Format("{0:HHmmss}", fView.FindViewById<EditText>(Resource.Id.txtStartTime).Text); // start time in format "HHmmss"
                    toTime = String.Format("{0:HHmmss}", fView.FindViewById<EditText>(Resource.Id.txtEndTime).Text);// end time in format "HHmmss"
                    fromDT = fromDate + fromTime;
                    ToDT = toDate + toTime;

                    if (!Check_DateTime(fromDate, toDate, fromTime, toTime)) return;
                    ExecuteFiscalCodeWithThread(() =>
                    {
                        ReadStrInfoByDates_Class_B(fromDT, ToDT);
                    });
                }
                
            });
        }



    }
}