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_C
{
    public class ElectronicJournalFragment : Android.Support.V4.App.Fragment
    {
        Button button;
        private View fView;
        private string document_Type = "A";
        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;
            DateTime startDate = DateTime.Today.AddDays(-1).Date;
            DateTime endDate = DateTime.Today.Date;
            fView.FindViewById<EditText>(Resource.Id.txtStartDate).Text = startDate.ToString("dd-MM-yy");
            fView.FindViewById<EditText>(Resource.Id.txtEndDate).Text = endDate.ToString("dd-MM-yy");
            fView.FindViewById<EditText>(Resource.Id.txtEndTime).Text = "23:00:00";
            fView.FindViewById<EditText>(Resource.Id.txtStartTime).Text = "23:59:59";
            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;


            if (fView.FindViewById<CheckBox>(Resource.Id.chkByDocNum).Checked)
            {
                fView.FindViewById<CheckBox>(Resource.Id.chkByDocNum).Enabled = true;


                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<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
            {
                fView.FindViewById<CheckBox>(Resource.Id.chkByDocNum).Enabled = true;
                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.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;
               

            }
        }

        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("dd-MM-yy");
                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("HH:mm:ss");
         });

            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
                        {
                            if (s.ErrorCode != -100003 && s.ErrorCode != -105000) // end of data
                                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)
            {// error in status bytes
                if (s.ErrorCode == -23)  CheckStatusErrorProperties();
                else
                {
                    if (s.ErrorCode != -100003 && s.ErrorCode != -105000)
                        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_PrintingMechanism) msg = msg + "\r\n" + MainActivity.fiscal.GetErrorMessage("-28");
                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_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_NotFound) msg = msg + "\r\n" + MainActivity.fiscal.GetErrorMessage("-40");
                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("dd-MM-yy");
                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("HH:mm:ss");
         });

            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<TextView>(Resource.Id.lblFromNum).Enabled = value;
                fView.FindViewById<TextView>(Resource.Id.lblToNum).Enabled = value;
                fView.FindViewById<EditText>(Resource.Id.txtFromNum).Enabled = value;
                fView.FindViewById<EditText>(Resource.Id.txtToNum).Enabled = value;
            }
        }

        private bool checkDocumentNumsBoxes()
        {
            string txtToNum = fView.FindViewById<EditText>(Resource.Id.txtToNum).Text;
            string txtFromNum = fView.FindViewById<EditText>(Resource.Id.txtFromNum).Text;
            
            
                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 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;
                           
                                string txtToNum = fView.FindViewById<EditText>(Resource.Id.txtToNum).Text;
                                string txtFromNum = fView.FindViewById<EditText>(Resource.Id.txtFromNum).Text;
                                ExecuteFiscalCodeWithThread(() =>
                                {
                                    GetEJDocsByNums(Int32.Parse(txtFromNum), Int32.Parse(txtToNum), int.Parse(document_Type));
                                });
                            
                        }
                        else
                        {

                            string firstDoc = "", lastDoc = "";
                            fromDate = String.Format("{0:dd-MM-yy}", fView.FindViewById<EditText>(Resource.Id.txtStartDate).Text); // start date in format "dd-MM-yy"
                            toDate = String.Format("{0:dd-MM-yy}", fView.FindViewById<EditText>(Resource.Id.txtEndDate).Text);// end date in format "dd-MM-yy"
                            fromTime = String.Format("{0:HH:mm:ss}", fView.FindViewById<EditText>(Resource.Id.txtStartTime).Text); // start time in format "HH:mm:ss"
                            toTime = String.Format("{0:HH:mm:ss}", fView.FindViewById<EditText>(Resource.Id.txtEndTime).Text);// end time in format "HH:mm:ss"
                            fromDT = fromDate + " " + fromTime;
                            ToDT = toDate + " " + toTime;
                            if (MainActivity.fiscal.ItIs_SummerDT(fromDT)) fromDT += " DST";
                            if (MainActivity.fiscal.ItIs_SummerDT(ToDT)) ToDT += " DST";
                            //inputValue = "R," + document_Type + "," + fromDT + "," + ToDT;
                            //---------------------

                            if (!Check_DateTime(fromDate, toDate, fromTime, toTime)) return;
                            ExecuteFiscalCodeWithThread(() =>
                            {
                                var result = MainActivity.fiscal.klen_Documents_InRange(fromDT, ToDT, document_Type);
                                // error_Code = fiscal.CustomCommand(119, inputValue);
                                if (result["firstDocumentNumber"] != "")
                                {
                                    firstDoc = result["firstDocumentNumber"];
                                    lastDoc = result["lastDocumentNumber"];
                                    GetEJDocsByNums(Int32.Parse(firstDoc), Int32.Parse(lastDoc), int.Parse(document_Type));
                                    
                                }
                               
                            });
                        }
                    });
        }

        private void GetEJDocsByNums(int startNum, int endNum, int docType)
        {
            
            Calculate_DocumentType();
            if (MainActivity.fiscal == null) return;
            if (!MainActivity.fiscal.device_Connected) return;
            if (fView == null) return;

            this.Activity.RunOnUiThread(() =>
            {
                prgAction.Visibility = Android.Views.ViewStates.Visible;
            });
            for (int i = startNum; i <= endNum; i++)
            {
                try
                {
                    
                    // command 125 - Information from EJ,reading by document number.                                
                    var result = MainActivity.fiscal.klen_SetDocument_ToRead("0", i.ToString(), docType.ToString());
                    if (result["errorCode"] != "0") break;
                    if (StopReading) break;

                    do
                    {
                        var res = MainActivity.fiscal.klen_GetLine_AsText("1"); // read line by line as text                               
                            
                        if (res["errorCode"] == "0")
                        {
                            string[] rowsData = res["textData"].Split(new string[] { "\r\n" }, StringSplitOptions.None);   // Get last answer list
                            
                                list.Add(rowsData[0] + "\r\n");
                            
                        }

                    } while (!StopReading);
                }
                catch (FiscalException ex)
                {
                    if (ex.ErrorCode != -105000 && ex.ErrorCode != -100003) throw; // -105000 and -100003 end of data
                    else
                    {
                        lstTitles.Add(i.ToString());
                        rej.Add(list.ToArray());
                        list.Clear();
                    }

                }
                this.Activity.RunOnUiThread(() =>
                {
                    lstReceiptsContainer.Adapter = new ArrayAdapter(MainActivity.GetInstance(), Resource.Layout.RecList_Item, lstTitles.ToArray());
                    lstReceiptsContainer.SetSelection(lstReceiptsContainer.Adapter.Count - 1);

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

        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<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");
        }

        private void ReadStrInfoByNums_DeviceGroup_C(string fromNum, string toNum)
        {
            string out_DocType = "";
            // id = 0;
            try
            {
                this.Activity.RunOnUiThread(() =>
                {
                    prgAction.Visibility = Android.Views.ViewStates.Visible;
                });
                for (int i = Int32.Parse(fromNum); i <= Int32.Parse(toNum); i++)
                {
                    if (StopReading) return;
                    if (document_Type == "10")
                    {
                        var result = MainActivity.fiscal.klen_SetCSVDocument_ToRead("9", i.ToString(), toNum);// ref out_ErrorCode, ref out_DocNum, ref out_RecNum, ref out_DT, ref out_DocType, ref out_ZNum);
                        out_DocType = result["docType"];
                        if (i != int.Parse(result["docNumber"]))
                        {
                            i = Int32.Parse(result["docNumber"]) - 1;
                            continue;
                        }
                    }
                    // сетва документ за четене
                    else if (document_Type == "5")
                    {
                        var res = MainActivity.fiscal.klen_SetDocument_ToRead("0", i.ToString(), "5");
                        if (res["errorCode"] == "-105000") continue;
                        if (res["errorCode"] != "0") return;
                        out_DocType = res["docType"];
                    }
                    else
                    {
                        var result2 = MainActivity.fiscal.klen_SetDocument_ToRead("0", i.ToString(), document_Type);
                        if (result2["errorCode"] != "0") return;
                        out_DocType = result2["docType"];
                    }
                    if (document_Type == "5")
                    {
                        if (out_DocType != "5") continue;
                    }

                    
                    //string[] res4 = {};
                    try
                    {
                        while (true)
                        {
                            // чете ред по ред структурирана информация
                            //result4 = MainActivity.fiscal.klen_GetLine_AsData("2");
                            var result4 = MainActivity.fiscal.CustomCommand(125, "2\t");
                             var res4 = result4.Split('\t');
                            if (res4[0] == "-100003") break;
                            if (StopReading) return;
                            if (res4[0] == "0")
                            {
                                if (res4[1] == null) return;
                                if (res4[1].Length == 0)
                                {
                                    this.Activity.RunOnUiThread(() =>
                                    {
                                        MainActivity.ShowMessage("There is no data into a last answer list.", "Warning");
                                    });
                                    return;
                                }
                                else
                                {
                                    byte[] data = System.Convert.FromBase64String(res4[1]);
                                    var c = new StructuredInfoRegister_DeviceGroup_C(data);
                                    ParseInfoFromStructure_C(c.Type, data);

                                }
                            }

                        }
                    }
                    catch (FiscalException ex)
                    {
                        if (ex.ErrorCode == -100003) break;
                    }
                    this.Activity.RunOnUiThread(() =>
                                {
                                    lstReceiptsContainer.Adapter = new ArrayAdapter(MainActivity.GetInstance(), Resource.Layout.RecList_Item, lstTitles.ToArray());
                                    lstReceiptsContainer.SetSelection(lstReceiptsContainer.Adapter.Count - 1);

                                });
                    if (!(list.Count == 0))
                    {
                        lstTitles.Add(i.ToString());
                        rej.Add(list.ToArray());
                    }
                    list.Clear();
                    if (StopReading) return;
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                this.Activity.RunOnUiThread(() =>
                {
                    prgAction.Visibility = Android.Views.ViewStates.Invisible;
                });
            }
        }

        private void ReadStrInfoByDates_DeviceGroup_C(string fromDT, string ToDT)
        {
            try
            {
                if (StopReading) return;
                this.Activity.RunOnUiThread(() =>
                {
                    prgAction.Visibility = Android.Views.ViewStates.Visible;
                });

                var result = MainActivity.fiscal.klen_Documents_InRange(fromDT, ToDT, document_Type);
                for (int i = Int32.Parse(result["firstDocumentNumber"]); i <= Int32.Parse(result["lastDocumentNumber"]); i++)
                {
                   
                    if (StopReading) return;
                    // използва се за проверка от кой тип е докуметът (параметър out_DocType) 
                    //и дали за текущия документ има структурирана информация или връща следващия такъв в параметър out_DocNum 

                    if (document_Type == "10")
                    {
                        var res = MainActivity.fiscal.klen_SetCSVDocument_ToRead("9", i.ToString(), result["lastDocumentNumber"]);

                        if (i != Int32.Parse(res["docNumber"]))
                        {
                            i = Int32.Parse(res["docNumber"]) - 1;
                            continue;
                        }
                    }

                    // сетваме документ за четене с проверения документен номер (i) и съответния тип на документа (out_DocType)
                    else if (document_Type == "5")
                    {
                        var resDoc = MainActivity.fiscal.klen_SetDocument_ToRead("0", i.ToString(), "5");
                    }

                    else
                    {
                        var resDoc = MainActivity.fiscal.klen_SetDocument_ToRead("0", i.ToString(), document_Type);
                    }
                    while (true)
                    {
                        // read structured info line by line
                        if (StopReading) return;
                        var res4 = MainActivity.fiscal.CustomCommand(125, "2\t"); //with custom command
                        var result4 = res4.Split('\t');
                        if (result4[0] == "-100003") break;
                        if(result4[0]=="0")
                        {
                            if(result4[1].Length == 0)
                            {
                                this.Activity.RunOnUiThread(() =>
                                {
                                    MainActivity.ShowMessage("There is no data into a last answer list.", "Warning");
                                });
                                return;
                            }
                            else
                            {
                                byte[] data = System.Convert.FromBase64String(result4[1]);
                                var c = new StructuredInfoRegister_DeviceGroup_C(data);
                                ParseInfoFromStructure_C(c.Type, data);
                               
                            }
                        }
                        
                    }
                    if (!(list.Count() == 0))
                    {
                        lstTitles.Add(i.ToString());
                        rej.Add(list.ToArray());
                    }
                    list.Clear();
                    this.Activity.RunOnUiThread(() =>
                    {
                        lstReceiptsContainer.Adapter = new ArrayAdapter(MainActivity.GetInstance(), Resource.Layout.RecList_Item, lstTitles.ToArray());
                        lstReceiptsContainer.SetSelection(lstReceiptsContainer.Adapter.Count - 1);
                    });
                    
                }
            }
            catch (FiscalException ex)
            {
                if (ex.ErrorCode != -105000 && ex.ErrorCode != -100003) throw;
                
            }
        }

        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();
        }

        public static string GetStringFromByteArr_Special(byte[] data)
        {
            return GetStringFromByteArr_2(data, 0);
        }

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

        public static string GetStringFromCharArr_Special(char[] full)
        {
            return GetStringFromCharArr_2(full, 0);
        }

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

        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);
        }

        private void ParseInfoFromStructure_C(StructuredInfoRegister_DeviceGroup_C.tagRClass type, byte[] data)
        {
            var c = new StructuredInfoRegister_DeviceGroup_C(data);
            switch (type)
            {
                case StructuredInfoRegister_DeviceGroup_C.tagRClass.UNKNOWN:
                    {
                        break;
                    }
                case StructuredInfoRegister_DeviceGroup_C.tagRClass.PLUSELL:
                case StructuredInfoRegister_DeviceGroup_C.tagRClass.DPxSELL:
                case StructuredInfoRegister_DeviceGroup_C.tagRClass.VD_PLUSELL:
                case StructuredInfoRegister_DeviceGroup_C.tagRClass.VD_DPxSELL:
                    {
                        var sell = c.CmdSell;
                        switch (type)
                        {

                            case StructuredInfoRegister_DeviceGroup_C.tagRClass.PLUSELL:
                                {
                                    list.Add("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" + "\r\n");
                                    list.Add("Продажба на артикул:\t" + "\r\n");
                                    list.Add("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" + "\r\n");
                                    break;
                                }
                            case StructuredInfoRegister_DeviceGroup_C.tagRClass.DPxSELL:
                                {
                                    list.Add("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" + "\r\n");
                                    list.Add("Продажба на департамент:\t" + "\r\n");
                                    list.Add("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" + "\r\n");
                                    break;
                                }
                            case StructuredInfoRegister_DeviceGroup_C.tagRClass.VD_PLUSELL:
                                {
                                    list.Add("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" + "\r\n");
                                    list.Add("Войд на продажба на артикул:\t" + "\r\n");
                                    list.Add("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" + "\r\n");
                                    break;
                                }
                            case StructuredInfoRegister_DeviceGroup_C.tagRClass.VD_DPxSELL:
                                {
                                    list.Add("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" + "\r\n");
                                    list.Add("Войд на продажба на департамент:\t" + "\r\n");
                                    list.Add("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" + "\r\n");
                                    break;
                                }
                        }

                        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");
                        var r = (sell.prc / 100).ToString() + "," + (sell.prc % 100).ToString("D2");
                        list.Add("Единична цена:\t" + r.ToString() + "\r\n");
                        var ro = (sell.suma / 100).ToString() + "," + (sell.suma % 100).ToString("D2");
                        list.Add("Сума:\t" + ro.ToString() + "\r\n"); // Сума = qty*prc   
                        list.Add("Номенклатурен код:\t" + sell.icode.ToString() + "\r\n");
                        list.Add("Баркод:\t" + sell.bcode.ToString() + "\r\n");
                        var qo = (sell.qty / 1000).ToString() + "," + (sell.qty % 1000).ToString("D2");
                        list.Add("Продадено количество:\t" + qo.ToString() + "\r\n");
                        list.Add("Име:\t" + GetStringFromCharArr(sell.name) + "\r\n");
                        list.Add("Тип отстъпка/надбавка:\t" + sell.typeIncDec.ToString() + "\r\n");
                        var pr = (sell.sIncDec / 100).ToString() + "," + (sell.sIncDec % 100).ToString("D2");
                        list.Add("Процент или стойност:\t" + sell.sIncDec.ToString() + "\r\n");
                        list.Add("Номер на департамент:\t" + sell.dep.ToString() + "\r\n");
                        list.Add("Номер на стокова група:\t" + sell.grp.ToString() + "\r\n");
                        list.Add("Мерна единица:\t" + sell.unit.ToString() + "\r\n");
                        list.Add("Сторно:\t" + sell.fVDstorno.ToString() + "\r\n");
                        list.Add("\r\n");
                        break;
                    }
                case StructuredInfoRegister_DeviceGroup_C.tagRClass.PAYMENT:
                    {
                        var pay = c.CmdPay;
                        list.Add("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" + "\r\n");
                        list.Add("Плащане:\t" + "\r\n");
                        list.Add("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" + "\r\n");
                        list.Add("Подтип:\t" + pay.subtype.ToString() + "\r\n");
                        var lv = GetStringFromByteArr_Special(pay.name_currency);
                        var eur = GetStringFromByteArr_2(pay.name_currency, lv.Length + 1);
                        list.Add("Име на валута:\t" + lv.ToString() + " " + eur.ToString() + "\r\n");
                        var inp = (pay.sInput / 100).ToString() + "," + (pay.sInput % 100).ToString("D2");
                        list.Add("Въведена сума:\t" + inp.ToString() + "\r\n");
                        var rst = (pay.sResto / 100).ToString() + "," + (pay.sResto % 100).ToString("D2");
                        list.Add("Ресто:\t" + rst.ToString() + "\r\n");
                        var rstf = (pay.sRestoForeign / 100).ToString() + "," + (pay.sRestoForeign % 100).ToString("D2");
                        list.Add("Ресто в алтернативна валута:\t" + rstf.ToString() + "\r\n");
                        var pyn = (pay.sPYN / 100).ToString() + "," + (pay.sPYN % 100).ToString("D2");
                        list.Add("Сума подадена от клиента в алт.валута:\t" + pyn.ToString() + "\r\n");
                        var pyos = (pay.sPYosnov / 100).ToString() + "," + (pay.sPYosnov % 100).ToString("D2");
                        list.Add("Сума преизчислена в осн.валута" + pyos.ToString() + "\r\n");
                        var tln = (pay.sTLneosn / 100).ToString() + "," + (pay.sTLneosn % 100).ToString("D2");
                        list.Add("Сума преизчислена според курса:\t" + tln.ToString() + "\r\n");
                        var resOsn = (pay.sumRestoOsnovna / 100).ToString() + "," + (pay.sumRestoOsnovna % 100).ToString("D2");
                        list.Add("Ресто, в основна, преизчислено спрямо курса:\t" + resOsn.ToString() + "\r\n");
                        var exc = (pay.sExchRate / 100000).ToString() + "," + (pay.sExchRate % 100000).ToString("D2");
                        list.Add("Курс на основна -> алт.валута:\t" + exc.ToString() + "\r\n");
                        var pname = GetStringFromCharArr_Special(pay.pay_name);
                        var payName = GetStringFromCharArr_2(pay.pay_name, pname.Length + 1);
                        list.Add("Име на плащането:\t" + pname.ToString() + " " + payName.ToString() + "\r\n" + "\r\n");
                        break;
                    }
                case StructuredInfoRegister_DeviceGroup_C.tagRClass.OTS_NDB:
                case StructuredInfoRegister_DeviceGroup_C.tagRClass.VD_OTS_NDB:
                    {
                        var discSurc = c.CmdPerc;
                        list.Add("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" + "\r\n");
                        list.Add("Корекции:\t" + "\r\n");
                        list.Add("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" + "\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");
                        var ssum = (discSurc.sSuma / 100).ToString() + "," + (discSurc.sSuma % 100).ToString("D2");
                        list.Add("Сума на транзакцията:\t" + ssum.ToString() + "\r\n");
                        var sstl = (discSurc.sSTL / 100).ToString() + "," + (discSurc.sSTL % 100).ToString("D2");
                        list.Add("Обща сума по дан. групи преди %STL:\t" + sstl.ToString() + "\r\n");
                        //foreach (var val in discSurc.sBRUT)
                        //{
                        //    r += val.ToString() + " ";

                        //}
                        list.Add("Брутна сума:\t" + "\r\n");
                        var sbrutA = (discSurc.sBRUT[0] / 100).ToString() + "," + (discSurc.sBRUT[0] % 100).ToString("D2");
                        var sbrutB = (discSurc.sBRUT[1] / 100).ToString() + "," + (discSurc.sBRUT[1] % 100).ToString("D2");
                        var sbrutC = (discSurc.sBRUT[2] / 100).ToString() + "," + (discSurc.sBRUT[2] % 100).ToString("D2");
                        var sbrutD = (discSurc.sBRUT[3] / 100).ToString() + "," + (discSurc.sBRUT[3] % 100).ToString("D2");
                        var sbrutE = (discSurc.sBRUT[4] / 100).ToString() + "," + (discSurc.sBRUT[4] % 100).ToString("D2");
                        var sbrutF = (discSurc.sBRUT[5] / 100).ToString() + "," + (discSurc.sBRUT[5] % 100).ToString("D2");
                        var sbrutG = (discSurc.sBRUT[6] / 100).ToString() + "," + (discSurc.sBRUT[6] % 100).ToString("D2");
                        var sbrutH = (discSurc.sBRUT[7] / 100).ToString() + "," + (discSurc.sBRUT[7] % 100).ToString("D2");

                        list.Add("По група А:\t" + sbrutA + "\r\n");
                        list.Add("По група Б:\t" + sbrutB + "\r\n");
                        list.Add("По група В:\t" + sbrutC + "\r\n");
                        list.Add("По група Г:\t" + sbrutD + "\r\n");
                        list.Add("По група Д:\t" + sbrutE + "\r\n");
                        list.Add("По група Е:\t" + sbrutF + "\r\n");
                        list.Add("По група Ж:\t" + sbrutG + "\r\n");
                        list.Add("По група З:\t" + sbrutH + "\r\n");
                        var perc = (discSurc.percIncDec / 100).ToString() + "," + (discSurc.percIncDec % 100).ToString("D2");
                        list.Add("Стойност на отстъпка/надбавка:\t" + perc.ToString() + "\r\n");
                        list.Add("Сторно:\t" + discSurc.fVDstorno.ToString() + "\r\n" + "\r\n");
                        break;
                    }
                case StructuredInfoRegister_DeviceGroup_C.tagRClass.RA_PO:
                    {
                        var rapo = c.CmdRapo;
                        list.Add("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" + "\r\n");
                        list.Add("Служебен внос / износ:\t" + "\r\n");
                        list.Add("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" + "\r\n");
                        list.Add("Подтип:\t" + rapo.subtype.ToString() + "\r\n");
                        var lv = GetStringFromByteArr_Special(rapo.name_currency);
                        var eur = GetStringFromByteArr_2(rapo.name_currency, lv.Length + 1);
                        list.Add("Име на валута:\t" + lv.ToString() + " " + eur.ToString() + "\r\n");
                        var sInp = (rapo.sInput / 100).ToString() + "," + (rapo.sInput % 100).ToString("D2");
                        list.Add("Въведена сума:\t" + sInp.ToString() + "\r\n");
                        var exc = (rapo.sExchRate / 100000).ToString() + "," + (rapo.sExchRate % 100000).ToString("D2");
                        list.Add("Курс на основна -> алт.валута:\t" + exc.ToString() + "\r\n" + "\r\n");
                        break;
                    }
                case StructuredInfoRegister_DeviceGroup_C.tagRClass.ABONAT:
                    {

                        var abonat = c.CmdAbonat;
                        list.Add("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" + "\r\n");
                        list.Add("Печат на номер на абонат:\t" + "\r\n");
                        list.Add("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" + "\r\n");
                        list.Add("Абонатен номер:\t" + GetStringFromCharArr(abonat.AbonatNomer) + "\r\n");
                        list.Add("Абонатна карта:\t" + GetStringFromCharArr(abonat.AbonatKarta) + "\r\n" + "\r\n");
                        break;
                    }
                case StructuredInfoRegister_DeviceGroup_C.tagRClass.BEGPAY:
                    {
                        string r = "";
                        var total = c.CmdTotal;
                        list.Add("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" + "\r\n");
                        list.Add("Начало на плащане:\t" + "\r\n");
                        list.Add("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" + "\r\n");
                        var lv = GetStringFromByteArr_Special(total.name_currency);
                        var eur = GetStringFromByteArr_2(total.name_currency, lv.Length + 1);
                        list.Add("Име на валута:\t" + lv.ToString() + " " + eur.ToString() + "\r\n");
                        var sstl = (total.sSTL / 100).ToString() + "," + (total.sSTL % 100).ToString("D2");
                        list.Add("Обща сума:\t" + sstl.ToString() + "\r\n");
                        //foreach (var val in total.sBRUT)
                        //{
                        //    r += val.ToString() + " ";

                        //}
                        list.Add("Брутна сума:\t" + "\r\n");
                        var sbrutA = (total.sBRUT[0] / 100).ToString() + "," + (total.sBRUT[0] % 100).ToString("D2");
                        var sbrutB = (total.sBRUT[1] / 100).ToString() + "," + (total.sBRUT[1] % 100).ToString("D2");
                        var sbrutC = (total.sBRUT[2] / 100).ToString() + "," + (total.sBRUT[2] % 100).ToString("D2");
                        var sbrutD = (total.sBRUT[3] / 100).ToString() + "," + (total.sBRUT[3] % 100).ToString("D2");
                        var sbrutE = (total.sBRUT[4] / 100).ToString() + "," + (total.sBRUT[4] % 100).ToString("D2");
                        var sbrutF = (total.sBRUT[5] / 100).ToString() + "," + (total.sBRUT[5] % 100).ToString("D2");
                        var sbrutG = (total.sBRUT[6] / 100).ToString() + "," + (total.sBRUT[6] % 100).ToString("D2");
                        var sbrutH = (total.sBRUT[7] / 100).ToString() + "," + (total.sBRUT[7] % 100).ToString("D2");

                        list.Add("По група А:\t" + sbrutA + "\r\n");
                        list.Add("По група Б:\t" + sbrutB + "\r\n");
                        list.Add("По група В:\t" + sbrutC + "\r\n");
                        list.Add("По група Г:\t" + sbrutD + "\r\n");
                        list.Add("По група Д:\t" + sbrutE + "\r\n");
                        list.Add("По група Е:\t" + sbrutF + "\r\n");
                        list.Add("По група Ж:\t" + sbrutG + "\r\n");
                        list.Add("По група З:\t" + sbrutH + "\r\n");
                        var exc = (total.sExchRate / 100000).ToString() + "," + (total.sExchRate % 100000).ToString("D2");
                        list.Add("Курс на основна -> алт.валута:\t" + exc.ToString() + "\r\n" + "\r\n");
                        break;
                    }
                case StructuredInfoRegister_DeviceGroup_C.tagRClass.ALL_VOID:
                    {
                        var allVoid = c.CmdAllVoid;
                        list.Add("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" + "\r\n");
                        list.Add("Анулиране на целия бон:\t" + "\r\n");
                        list.Add("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" + "\r\n");
                        var sstl = (allVoid.sTL / 100).ToString() + "," + (allVoid.sTL % 100).ToString("D2");
                        list.Add("Обща сума:\t" + sstl.ToString() + "\r\n");
                        //foreach (var val in allVoid.sBRUT)
                        //{
                        //    r += val.ToString() + " ";

                        //}
                        list.Add("Брутна сума:\t" + "\r\n");
                        var sbrutA = (allVoid.sBRUT[0] / 100).ToString() + "," + (allVoid.sBRUT[0] % 100).ToString("D2");
                        var sbrutB = (allVoid.sBRUT[1] / 100).ToString() + "," + (allVoid.sBRUT[1] % 100).ToString("D2");
                        var sbrutC = (allVoid.sBRUT[2] / 100).ToString() + "," + (allVoid.sBRUT[2] % 100).ToString("D2");
                        var sbrutD = (allVoid.sBRUT[3] / 100).ToString() + "," + (allVoid.sBRUT[3] % 100).ToString("D2");
                        var sbrutE = (allVoid.sBRUT[4] / 100).ToString() + "," + (allVoid.sBRUT[4] % 100).ToString("D2");
                        var sbrutF = (allVoid.sBRUT[5] / 100).ToString() + "," + (allVoid.sBRUT[5] % 100).ToString("D2");
                        var sbrutG = (allVoid.sBRUT[6] / 100).ToString() + "," + (allVoid.sBRUT[6] % 100).ToString("D2");
                        var sbrutH = (allVoid.sBRUT[7] / 100).ToString() + "," + (allVoid.sBRUT[7] % 100).ToString("D2");

                        list.Add("По група А:\t" + sbrutA + "\r\n");
                        list.Add("По група Б:\t" + sbrutB + "\r\n");
                        list.Add("По група В:\t" + sbrutC + "\r\n");
                        list.Add("По група Г:\t" + sbrutD + "\r\n");
                        list.Add("По група Д:\t" + sbrutE + "\r\n");
                        list.Add("По група Е:\t" + sbrutF + "\r\n");
                        list.Add("По група Ж:\t" + sbrutG + "\r\n");
                        list.Add("По група З:\t" + sbrutH + "\r\n");
                        break;
                    }
                case StructuredInfoRegister_DeviceGroup_C.tagRClass.TEXT_LINE:
                    {
                        var textLine = c.CmdTextLine;
                        list.Add("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" + "\r\n");
                        list.Add("Печат на текстов ред:\t" + "\r\n");
                        list.Add("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" + "\r\n");
                        list.Add("Текст:\t" + GetStringFromByteArr(textLine.text) + "\r\n" + "\r\n");
                        break;
                    }
                case StructuredInfoRegister_DeviceGroup_C.tagRClass.OPEN_BON:
                    {
                        var open = c.CmdOpen;
                        list.Add("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" + "\r\n");
                        list.Add("Отваряне на бон:\t" + "\r\n");
                        list.Add("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" + "\r\n");
                        list.Add("Подтип:\t" + open.subtype.ToString() + "\r\n");
                        list.Add("Номер на оператор:\t" + open.nClerk.ToString() + "\r\n");
                        list.Add("Тип сторно:\t" + open.stornoType.ToString() + "\r\n");
                        list.Add("Позиция на десетичната точка:\t" + open.dec_point.ToString() + "\r\n");
                        list.Add("Номер на фактура, към която е сторното:\t" + open.nInvoice.ToString() + "\r\n");
                        list.Add("Номер на фактура, по който е сторното:\t" + open.nInvoiceStorno.ToString() + "\r\n");
                        list.Add("Номер на бона, по който е сторното:\t" + open.strNumberDoc.ToString() + "\r\n");
                        list.Add("Дата и час:\t" + StructuredInfoRegister_DeviceGroup_C.DateToString(open.bonDateTime) + "\r\n");
                        list.Add("Дата и час на сторното:\t" + StructuredInfoRegister_DeviceGroup_C.DateToString(open.strDateTime) + "\r\n");
                        list.Add("Карта на плащанията:\t");
                        for (int i = 0; i < open.paymentRemap.Length; i++)
                        {
                            list.Add(open.paymentRemap[i].ToString() + " ");
                        }
                        list.Add("\r\n");
                        list.Add("Номер на фискалната памет на бона:\t" + GetStringFromCharArr(open.strFMnumber) + "\r\n");
                        list.Add("Уникален номер на продажба:\t" + GetStringFromCharArr(open.nSale) + "\r\n" + "\r\n");

                        break;
                    }

                case StructuredInfoRegister_DeviceGroup_C.tagRClass.CLOSE_BON:
                    {
                        var close = c.CmdClose;
                        list.Add("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" + "\r\n");
                        list.Add("Затваряне на бон:\t" + "\r\n");
                        list.Add("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" + "\r\n");
                        list.Add("Подтип:\t" + close.subtype.ToString() + "\r\n");
                        list.Add("Тип лична информация:\t" + close.ClientEikType.ToString() + "\r\n");
                        list.Add("Номер на фактура:\t" + close.nInvoice.ToString() + "\r\n");
                        list.Add("Дата и час:\t" + StructuredInfoRegister_DeviceGroup_C.DateToString(close.bonDateTime) + "\r\n");
                        list.Add("Лична клиентска информация:\t" + GetStringFromCharArr(close.clientEIK) + "\r\n");
                        list.Add("Идентификационен номер:\t" + GetStringFromCharArr(close.IDnumber) + "\r\n");
                        break;
                    }

                case StructuredInfoRegister_DeviceGroup_C.tagRClass.INVOICE:
                    {
                        var invoice = c.CmdInvoice;
                        list.Add("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" + "\r\n");
                        list.Add("Информация за фактура:\t" + "\r\n");
                        list.Add("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" + "\r\n");
                        list.Add("Номер на фактура:\t" + invoice.invoiceNumber.ToString() + "\r\n" + "\r\n");
                        break;
                    }

                case StructuredInfoRegister_DeviceGroup_C.tagRClass.ADD_INFO:
                    {
                        var addInfo = c.CmdAddInfo;
                        list.Add("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" + "\r\n");
                        list.Add("Допълнителна информация:\t" + "\r\n");
                        list.Add("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" + "\r\n");
                        list.Add("Бонус:\t" + GetStringFromCharArr(addInfo.bonus) + "\r\n");
                        list.Add("Име:\t" + GetStringFromCharArr(addInfo.name) + "\r\n");
                        list.Add("Брой данъчни групи:\t" + GetStringFromCharArr(addInfo.TaxN) + "\r\n");
                        list.Add("Тип данъчни групи:\t" + addInfo.typeTaxN.ToString() + "\r\n");
                        list.Add("Име на получател:\t" + GetStringFromCharArr(addInfo.RECname) + "\r\n");
                        list.Add("Брой данъчни групи:\t" + GetStringFromCharArr(addInfo.VATN) + "\r\n" + "\r\n");
                        break;
                    }

                case StructuredInfoRegister_DeviceGroup_C.tagRClass.CARGO:
                    {
                        var cargo = c.CmdCargo;
                        list.Add("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" + "\r\n");
                        list.Add("Товарителница:\t" + "\r\n");
                        list.Add("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" + "\r\n");
                        list.Add("Товарителница:\t" + GetStringFromCharArr(cargo.tovaritelnica) + "\r\n" + "\r\n");
                        break;
                    }

                case StructuredInfoRegister_DeviceGroup_C.tagRClass.BONUS:
                    {
                        var bonus = c.CmdBonus;
                        list.Add("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" + "\r\n");
                        list.Add("Бонус текст към продажбата:\t" + "\r\n");
                        list.Add("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" + "\r\n");
                        list.Add("Подтип:\t" + bonus.index.ToString() + "\r\n" + "\r\n");
                        break;
                    }

                case StructuredInfoRegister_DeviceGroup_C.tagRClass.BARCODE_LINE:
                    {
                        var barcode = c.CmdBarcodeLine;
                        list.Add("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" + "\r\n");
                        list.Add("Баркод:\t" + "\r\n");
                        list.Add("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" + "\r\n");
                        list.Add("Подтип:\t" + barcode.subtype.ToString() + "\r\n");
                        list.Add("Текст base64 формат:\t" + GetStringFromCharArr(barcode.base64Text) + "\r\n" + "\r\n");
                        break;
                    }
                    /*
                case StructuredInfoRegister_DeviceGroup_C.tagRClass.HEADER_FOOTER:
                    {
                        var headerFooter = c.CmdHeaderFooter;
                        rtxEJ.SelectionFont = new Font(rtxEJ.Font, FontStyle.Bold);
                        rtxEJ.AppendText("Header and footer:\t" + "\r\n");
                        rtxEJ.AppendText("Подтип:\t" + headerFooter.subtype.ToString() + "\r\n");
                        rtxEJ.AppendText("Номер на ред:\t" + headerFooter.nLine.ToString() + "\r\n");
                        rtxEJ.AppendText("Текст за отпечатване:\t" + GetStringFromCharArr(headerFooter.text) + "\r\n");
                        rtxEJ.AppendText("Контролна сума:\t" + headerFooter.checksum.ToString() + "\r\n" + "\r\n");
                        break;
                    }
                case StructuredInfoRegister_DeviceGroup_C.tagRClass.PINPAD_INFO:
                    {
                        //не се използва
                        break;
                    }
                    */
            }
        }
       
        private bool Check_DateTime(string stD, string endD, string stT, string endT)
        {
            SimpleDateFormat formatStart = new SimpleDateFormat("dd-MM-yy");
            SimpleDateFormat formatEnd = new SimpleDateFormat("dd-MM-yy");
            SimpleDateFormat formatStartTime = new SimpleDateFormat("HH:mm:ss");
            SimpleDateFormat formatEndTime = new SimpleDateFormat("HH:mm:ss");

            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;     // all types
                case 1: document_Type = "1"; break;     // fiscal receipts
                case 2: document_Type = "2"; break;     //daily Z report
                case 3: document_Type = "3"; break;     //invoice receipts
                case 4: document_Type = "4"; break;     //non - fiscal receipts
                case 5: document_Type = "5"; break;     //paidout receipts
                case 6: document_Type = "6"; break;     //STORNO fiscal receipts
                case 7: document_Type = "7"; break;     //STORNO invoice receipts
                case 8: document_Type = "8"; break;     //cancelled receipts (all voided)
                case 9: document_Type = "9"; break;     // daily X reports
                case 10: document_Type = "10"; break;   //fiscal receipts, invoice receipts, fiscal receipts - storno and invoice receipts - storno
            }
            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;
                    
                        string txtToNum = fView.FindViewById<EditText>(Resource.Id.txtToNum).Text;
                        string txtFromNum = fView.FindViewById<EditText>(Resource.Id.txtFromNum).Text;
                        ExecuteFiscalCodeWithThread(() =>
                        {
                            for (int i = int.Parse(txtFromNum); i <= int.Parse(txtToNum); i++)
                            {
                                try
                                {
                                    var result = MainActivity.fiscal.klen_Print_Document("3", i.ToString(), document_Type);
                                    // error -105000: ERR_EJ_NO_RECORDS - No records in electronic journal
                                    // error -100003: ERR_END_OF_DATA - End of data in electronic journal
                                    if ((result["errorCode"] == "-105000") || (result["errorCode"] == "-100003"))
                                    {
                                        if (int.Parse(txtToNum) < i) break;
                                        else continue;
                                    }

                                    if (StopReading) break;
                                }
                                catch (FiscalException ex)
                                {
                                    if (ex.ErrorCode != -105000 && ex.ErrorCode != -100003)
                                        this.Activity.RunOnUiThread(() =>
                                        {
                                            MainActivity.ShowMessage("Operation failed with: " + MainActivity.fiscal.GetErrorMessage(ex.ErrorCode.ToString()), "Error");
                                        });

                                }
                            }
                        });
                   
                }
                else
                {


                    fromDate = String.Format("{0:dd-MM-yy}", fView.FindViewById<EditText>(Resource.Id.txtStartDate).Text); // start date in format "dd-MM-yy"
                    toDate = String.Format("{0:dd-MM-yy}", fView.FindViewById<EditText>(Resource.Id.txtEndDate).Text);// end date in format "dd-MM-yy"
                    fromTime = String.Format("{0:HH:mm:ss}", fView.FindViewById<EditText>(Resource.Id.txtStartTime).Text); // start time in format "HH:mm:ss"
                    toTime = String.Format("{0:HH:mm:ss}", fView.FindViewById<EditText>(Resource.Id.txtEndTime).Text);// end time in format "HH:mm:ss"
                    fromDT = fromDate + fromTime;
                    ToDT = toDate + toTime;

                    if (!Check_DateTime(fromDate, toDate, fromTime, toTime)) return;
                    string inputValue = "P,>" + document_Type + "," + fromDT + "," + ToDT;
                    ExecuteFiscalCodeWithThread(() =>
                    {
                        var res = MainActivity.fiscal.CustomCommand(119, inputValue);
                        //error_Code = Generated_DeviceGroupA.execute_119_klen_Print_DocsFromDateToDate(serv, "P", ">", document_Type, fromDT, ToDT, ref answer);
                    });
                }
            });
        }
        private void BtnStop_Click(object sender, EventArgs e)
        {
            StopReading = true;
            ManageEJControls(true);
            Calculate_Controls();
        }
        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;

            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_DeviceGroup_C(txtFromNum, txtToNum);
                            
                        });
                }
                else
                {

                    fromDate = String.Format("{0:dd-MM-yy}", fView.FindViewById<EditText>(Resource.Id.txtStartDate).Text); // start date in format "dd-MM-yy"
                    toDate = String.Format("{0:dd-MM-yy}", fView.FindViewById<EditText>(Resource.Id.txtEndDate).Text);// end date in format "dd-MM-yy"
                    fromTime = String.Format("{0:HH:mm:ss}", fView.FindViewById<EditText>(Resource.Id.txtStartTime).Text); // start time in format "HH:mm:ss"
                    toTime = String.Format("{0:HH:mm:ss}", fView.FindViewById<EditText>(Resource.Id.txtEndTime).Text);// end time in format "HH:mm:ss"
                    fromDT = fromDate + " " + fromTime;
                    ToDT = toDate + " " + toTime;

                    if (!Check_DateTime(fromDate, toDate, fromTime, toTime)) return;

                    ExecuteFiscalCodeWithThread(() =>
                    {
                        ReadStrInfoByDates_DeviceGroup_C(fromDT, ToDT);
                       
                    });
                }
            });
        }



    }
}