using System;
using Newtonsoft.Json;
using System.Configuration;
using Nuvolar.Module;
using DevExpress.Xpo;
using DevExpress.Data.Filtering;
using DevExpress.Persistent.Base;
using DevExpress.Xpo.DB;
using DevExpress.Persistent.BaseImpl;
using System.IO;

namespace Nuvolar.Scanner.Module.CSharp
{
    public class ScannerModule
    {
        private DevExpress.Xpo.Session _session;
        public ScannerModule()
        {
            _session = new DevExpress.Xpo.Session();
            _session.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            _session.AutoCreateOption = DevExpress.Xpo.DB.AutoCreateOption.SchemaAlreadyExists;
        }
        public String GetInfo(String I)
        {
            SimpleAnswer _SimpleAnswer = new SimpleAnswer();
            SimpleQuery _SimpleQuery = JsonConvert.DeserializeObject<SimpleQuery>(I);

            if (_SimpleQuery.Query == "DX_Login")
            {
                if (this.DX_Login(_SimpleQuery.UserName, _SimpleQuery.Password, _SimpleQuery.Database))
                {
                    _SimpleAnswer.ResultStatus = 1;
                    _SimpleAnswer.Result = "OK";
                }
            }
            if (_SimpleQuery.Query == "DX_GetStoragePDACollectionHeader_dxList")
            {
                _SimpleAnswer.ResultStatus = 1;
                _SimpleAnswer.Result = this.DX_GetStoragePDACollectionHeader_dxList(_SimpleQuery.Database);
            }
            if (_SimpleQuery.Query == "DX_GetStorageLocationFoldSelect_dxList")
            {
                _SimpleAnswer.ResultStatus = 1;
                _SimpleAnswer.Result = this.DX_GetStorageLocationFoldSelect_dxList(_SimpleQuery.Database);
            }
            
            if (_SimpleQuery.Query == "DX_GetStorageOutHeader_dxList")
            {
                _SimpleAnswer.ResultStatus = 1;
                _SimpleAnswer.Result = this.DX_GetStorageOutHeader_dxList(_SimpleQuery.Database);
            }
            if (_SimpleQuery.Query.Contains("DX_GetStoragePDACollectionRows_dxDataGrid"))
            {
                string[] _sArray = _SimpleQuery.Query.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
                _SimpleAnswer.ResultStatus = 1;
                _SimpleAnswer.Result = this.DX_GetStoragePDACollectionRows_dxDataGrid(Guid.Parse(_sArray[1]), _SimpleQuery.Database);
            }
            if (_SimpleQuery.Query.Contains("DX_GetProductsInfo_Picture"))
            {
                string[] _sArray = _SimpleQuery.Query.Split(new string[]{";"},StringSplitOptions.RemoveEmptyEntries);

                _SimpleAnswer.ResultStatus = 1;
                _SimpleAnswer.Result = this.DX_GetProductsInfo_Picture(_sArray[1], _SimpleQuery.Database);
            }
            if (_SimpleQuery.Query.Contains("DX_GetProductsInfo_dxDatagrid"))
            {
                string[] _sArray = _SimpleQuery.Query.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);

                _SimpleAnswer.ResultStatus = 1;
                _SimpleAnswer.Result = this.DX_GetProductsInfo_dxDatagrid(_sArray[1], _SimpleQuery.Database);
            }
            if (_SimpleQuery.Query.Contains("DX_GetDiscountInfo_dxDatagrid"))
            {
                string[] _sArray = _SimpleQuery.Query.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
                _SimpleAnswer.ResultStatus = 1;
                _SimpleAnswer.Result = this.DX_GetDiscountInfo_dxDatagrid(_sArray[1], _SimpleQuery.Database);
            }
            if (_SimpleQuery.Query.Contains("DX_InsertStoragePDACollectionRows_dxDataGrid"))
            {
                string[] _sArray = _SimpleQuery.Query.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
                _SimpleAnswer.ResultStatus = 1;
                _SimpleAnswer.Result = this.DX_InsertStoragePDACollectionRows_dxDataGrid(_sArray[1], Guid.Parse(_sArray[2]), int.Parse(_sArray[3]), _SimpleQuery.Database);
            }
            if (_SimpleQuery.Query.Contains("DX_InsertStorageLocationFold_dxDataGrid"))
            {
                string[] _sArray = _SimpleQuery.Query.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
                _SimpleAnswer.ResultStatus = 1;
                _SimpleAnswer.Result = this.DX_InsertStorageLocationFold_dxDataGrid(_sArray[1], Guid.Parse(_sArray[2]),int.Parse(_sArray[3]),_sArray[4], _SimpleQuery.Database);
            }
            
            if (_SimpleQuery.Query.Contains("DX_DeleteStoragePDACollectionRows_dxDataGrid"))
            {
                string[] _sArray = _SimpleQuery.Query.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
                _SimpleAnswer.ResultStatus = 1;
                _SimpleAnswer.Result =  this.DX_DeleteStoragePDACollectionRows_dxDataGrid(Guid.Parse(_sArray[1]), _SimpleQuery.Database);
            }
            if (_SimpleQuery.Query.Contains("DX_InsertDiscount_dxDataGrid"))
            {
                string[] _sArray = _SimpleQuery.Query.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
                _SimpleAnswer.ResultStatus = 1;
                _SimpleAnswer.Result = this.DX_InsertDiscount_dxDataGrid(_sArray[1], int.Parse(_sArray[2]), _sArray[3], _sArray[4], _SimpleQuery.Database);
            }

            if (_SimpleQuery.Query.Contains("DX_InsertStorageOutRows_dxDataGrid"))
            {
                string[] _sArray = _SimpleQuery.Query.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
                _SimpleAnswer.ResultStatus = 1;
                _SimpleAnswer.Result = this.DX_InsertStorageOutRows_dxDataGrid(_sArray[1], Guid.Parse(_sArray[2]), int.Parse(_sArray[3]), _SimpleQuery.Database);
            }
            if (_SimpleQuery.Query.Contains("DX_GetStorageOutRows_dxDataGrid"))
            {
                string[] _sArray = _SimpleQuery.Query.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
                _SimpleAnswer.ResultStatus = 1;
                _SimpleAnswer.Result = this.DX_GetStorageOutRows_dxDataGrid(Guid.Parse(_sArray[1]), _SimpleQuery.Database);
            }
            if (_SimpleQuery.Query.Contains("DX_DeleteStorageOutRows_dxDataGrid"))
            {
                string[] _sArray = _SimpleQuery.Query.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
                _SimpleAnswer.ResultStatus = 1;
                _SimpleAnswer.Result = "OK";
                this.DX_DeleteStorageOutRows_dxDataGrid(Guid.Parse(_sArray[1]), _SimpleQuery.Database);

            }
            return JsonConvert.SerializeObject(_SimpleAnswer);
        }

        private string DX_InsertStorageLocationFold_dxDataGrid(string BarcodeProducts, Guid _StoragePDACollectionHeaderGUID, double _QTT, string BarcodeLocations,string _SQLDatabase)
        {
            BarcodeProducts = BarcodeProducts.ToString().Replace("ö", "0");
            if (_session.IsConnected == true) { _session.Disconnect(); }
            _session.Connect();
            if (_session.IsConnected == true)
            {
                ProductsBarcodes _ProductsBarcodes = _session.FindObject<ProductsBarcodes>(CriteriaOperator.Parse("Barcode=?", BarcodeProducts));
                if (_ProductsBarcodes != null)
                {
                    StorageLocation _StorageLocation = _session.FindObject<StorageLocation>(CriteriaOperator.Parse("Barcode=?", BarcodeLocations));
                    if (_StorageLocation!=null)
                    {
                        StoragePDACollectionHeader _StoragePDACollectionHeader = _session.GetObjectByKey<StoragePDACollectionHeader>(_StoragePDACollectionHeaderGUID);
                        if (_StoragePDACollectionHeader!=null)
                        {
                            //Először azokat a sorokat kell megkeresni, ahol nincs lokáció és ez az aktuális vonalkód

                            foreach (StoragePDACollectionRows _StoragePDACollectionRows in _StoragePDACollectionHeader.StoragePDACollectionRows)
	                            {

		 
	                            }
                        }
                    }
                }
            }
            return this.DX_GetStoragePDACollectionRows_dxDataGrid(_StoragePDACollectionHeaderGUID, _SQLDatabase);
        }
        private string DX_GetStorageLocationFoldSelect_dxList(string database)
        {
            String _Result = null;
            if (_session.IsConnected == true) { _session.Disconnect(); }
            _session.Connect();
            if (_session.IsConnected == true)
            {
                XPCollection<StoragePDACollectionHeader> _StoragePDACollectionHeader_Collection = new XPCollection<StoragePDACollectionHeader>(_session, 
                    CriteriaOperator.Parse("StoragePDACollectionHeaderStatus=0 and StorageCollectionType=1"));
                if (_StoragePDACollectionHeader_Collection.Count > 0)
                {
                    _Result = "[";
                    foreach (StoragePDACollectionHeader _StoragePDACollectionHeader in _StoragePDACollectionHeader_Collection)
                    {
                        if (_Result == "[")
                        {
                            _Result += string.Format("{{ 'key': '{0}', 'title': '{1}'}}", _StoragePDACollectionHeader.Oid.ToString(), _StoragePDACollectionHeader.DocumentNumber);
                        }
                        else
                        {
                            _Result += string.Format(",{{ 'key': '{0}', 'title': '{1}'}}", _StoragePDACollectionHeader.Oid.ToString(), _StoragePDACollectionHeader.DocumentNumber);
                        }
                    }
                    _Result += "]";
                }
            }
            if (_Result != null)
            {
                _Result = _Result.Replace("'", ((char)34).ToString());
            }
            return _Result;
        }

        private void DX_DeleteStorageOutRows_dxDataGrid(Guid guid, string database)
        {
            throw new NotImplementedException();
        }
        private string DX_GetStorageOutRows_dxDataGrid(Guid guid, string database)
        {
            throw new NotImplementedException();
        }
        private string DX_InsertStorageOutRows_dxDataGrid(string v, Guid guid, object p, string database)
        {
            throw new NotImplementedException();
        }
        private string DX_InsertDiscount_dxDataGrid(string v1, object p, string v2, string v3, string database)
        {
            throw new NotImplementedException();
        }

        #region StoragePDACollection
        private string DX_GetStoragePDACollectionHeader_dxList(string database)
        {
            String _Result = null;
            if (_session.IsConnected == true) { _session.Disconnect(); }
            _session.Connect();
            if (_session.IsConnected == true)
            {
                XPCollection<StoragePDACollectionHeader> _StoragePDACollectionHeader_Collection = new XPCollection<StoragePDACollectionHeader>(_session, CriteriaOperator.Parse("StoragePDACollectionHeaderStatus=0"));
                if (_StoragePDACollectionHeader_Collection.Count > 0)
                {
                    _Result = "[";
                    foreach (StoragePDACollectionHeader _StoragePDACollectionHeader in _StoragePDACollectionHeader_Collection)
                    {
                        if (_Result == "[")
                        {
                            _Result += string.Format("{{ 'key': '{0}', 'title': '{1}'}}", _StoragePDACollectionHeader.Oid.ToString(), _StoragePDACollectionHeader.DocumentNumber);
                        }
                        else
                        {
                            _Result += string.Format(",{{ 'key': '{0}', 'title': '{1}'}}", _StoragePDACollectionHeader.Oid.ToString(), _StoragePDACollectionHeader.DocumentNumber);
                        }
                    }
                    _Result += "]";
                }
            }
            if (_Result != null)
            {
                _Result = _Result.Replace("'", ((char)34).ToString());
            }
            return _Result;
        }
        private string DX_InsertStoragePDACollectionRows_dxDataGrid(string _Barcode, Guid _StoragePDACollectionHeader, double _QTT, string _SQLDatabase)
        {
            _Barcode = _Barcode.ToString().Replace("ö", "0");
            if (_session.IsConnected == true) { _session.Disconnect(); }
            _session.Connect();
            if (_session.IsConnected == true)
            {
                ProductsBarcodes _ProductsBarcodes = _session.FindObject<ProductsBarcodes>(CriteriaOperator.Parse("Barcode=?", _Barcode));
                if (_ProductsBarcodes != null)
                {
                    StoragePDACollectionRows _StoragePDACollectionRows = new StoragePDACollectionRows(_session);
                    _StoragePDACollectionRows.StoragePDACollectionHeader = _session.GetObjectByKey<StoragePDACollectionHeader>(_StoragePDACollectionHeader);
                    _StoragePDACollectionRows.Barcode = _Barcode;
                    _StoragePDACollectionRows.Products = _ProductsBarcodes.Products;
                    _StoragePDACollectionRows.QTT = _QTT;
                    _StoragePDACollectionRows.Save();
                }
            }
            return this.DX_GetStoragePDACollectionRows_dxDataGrid(_StoragePDACollectionHeader, _SQLDatabase);
        }
        private string DX_DeleteStoragePDACollectionRows_dxDataGrid(Guid _StoragePDACollectionRows, string _SQLDatabase)
        {
            StoragePDACollectionHeader _StoragePDACollectionHeader = null;
            if (_session.IsConnected == true) { _session.Disconnect(); }
            _session.Connect();
            if (_session.IsConnected == true)
            {
                StoragePDACollectionRows _StoragePDACollectionRowsC = _session.FindObject<StoragePDACollectionRows>(CriteriaOperator.Parse("Oid=?", _StoragePDACollectionRows));
                if (_StoragePDACollectionRowsC!=null)
                {
                    _StoragePDACollectionHeader = _StoragePDACollectionRowsC.StoragePDACollectionHeader;
                }
                _session.Delete(_session.FindObject<StoragePDACollectionRows>(CriteriaOperator.Parse("Oid=?", _StoragePDACollectionRows)));
            }
            if (_StoragePDACollectionHeader == null)
            {
                return null;
            }
            else
            {
                return this.DX_GetStoragePDACollectionRows_dxDataGrid(_StoragePDACollectionHeader.Oid, _SQLDatabase);
            }
            
        }
        private string DX_GetStoragePDACollectionRows_dxDataGrid(Guid guid, string database)
        {
            String _Result = null;
            if (_session.IsConnected == true) { _session.Disconnect(); }
            _session.Connect();
            if (_session.IsConnected == true)
            {
                XPCollection<StoragePDACollectionRows> _StoragePDACollectionRows_Collection = new XPCollection<StoragePDACollectionRows>(_session,
                    CriteriaOperator.Parse("StoragePDACollectionHeader.Oid=?", guid));
                if (_StoragePDACollectionRows_Collection.Count > 0)
                {
                    _Result = "[";
                    foreach (StoragePDACollectionRows _StoragePDACollectionRows in _StoragePDACollectionRows_Collection)
                    {
                        if (_Result == "[")
                        {
                            _Result += string.Format("{{ 'Oid': '{0}', 'Barcode': '{1}','ShortName': '{2}','QTT': '{3}','RowIndex': '{4}' }}",
                                _StoragePDACollectionRows.Oid.ToString(), _StoragePDACollectionRows.Barcode, _StoragePDACollectionRows.Products.ShortName, _StoragePDACollectionRows.QTT, _StoragePDACollectionRows.RowIndex);
                        }
                        else
                        {
                            _Result += string.Format(",{{ 'Oid': '{0}', 'Barcode': '{1}','ShortName': '{2}','QTT': '{3}','RowIndex': '{4}' }}",
                                _StoragePDACollectionRows.Oid.ToString(), _StoragePDACollectionRows.Barcode, _StoragePDACollectionRows.Products.ShortName, _StoragePDACollectionRows.QTT, _StoragePDACollectionRows.RowIndex);
                        }
                    }
                    _Result += "]";
                }
            }
            if (_Result != null)
            {
                _Result = _Result.Replace("'", ((char)34).ToString());
            }
            return _Result;
        }
        #endregion

        private string DX_GetDiscountInfo_dxDatagrid(string v, string database)
        {
            throw new NotImplementedException();
        }

        private string DX_GetProductsInfo_Picture(string _Barcode, string _Database)
        {
            string _ProductPicture = "";
            ProductsBarcodes _ProductsBarcode = _session.FindObject<ProductsBarcodes>(CriteriaOperator.Parse("Barcode=?", _Barcode));
            if (_ProductsBarcode!=null)
            { 
                if (_ProductsBarcode.Products.Picture_FullSize!=null)
                {
                    MemoryStream _MemoryStream = new MemoryStream();
                    _ProductsBarcode.Products.Picture_FullSize.Save(_MemoryStream, System.Drawing.Imaging.ImageFormat.Png);
                    _ProductPicture= System.Convert.ToBase64String(_MemoryStream.ToArray());
                }
            }
            return _ProductPicture;
        }
        private string DX_GetProductsInfo_dxDatagrid(object p, string database)
        {
            p = p.ToString().Replace("ö", "0");
            String _Result = string.Format("[{{ 'Oid': '{0}', 'ShortName': '<NINCS>', 'Value': '<NINCS>'}}]", Guid.NewGuid().ToString());
            if (_session.IsConnected == true) { _session.Disconnect(); }
            _session.Connect();
            if (_session.IsConnected == true)
            {
                Products _Products=_session.FindObject<Products>(CriteriaOperator.Parse("Barcode=?", p));
                if (_Products == null)
                {
                    ProductsBarcodes _ProductsBarcodes= _session.FindObject<ProductsBarcodes>(CriteriaOperator.Parse("Barcode=?", p));
                    if (_ProductsBarcodes == null)
                    {
                        _Products = _session.FindObject<Products>(CriteriaOperator.Parse("ProductNumber = ?", p));
                        if (_Products == null)
                        {
                            //_Products = _session.FindObject<Products>(CriteriaOperator.Parse(string.Format("ShortName LIKE '%{0}%'", p)));
                        }
                    }
                    else
                    {
                        _Products = _ProductsBarcodes.Products;
                    }
                }
                if (_Products!=null)
                {
                    _Result = "[";
                    _Result += string.Format("{{ 'Oid': '{0}', 'ShortName': 'Cikkszám', 'Value': '{1}' }},", Guid.NewGuid().ToString(),_Products.ProductNumber);
                    _Result += string.Format("{{ 'Oid': '{0}', 'ShortName': 'Megnevezés', 'Value': '{1}' }},", Guid.NewGuid().ToString(),_Products.ShortName);
                    _Result += string.Format("{{ 'Oid': '{0}', 'ShortName': 'Ár', 'Value': '{1}' }}", Guid.NewGuid().ToString(), _Products.ListPriceOutHUF.ToString());
                    /*_Result += string.Format("{ 'Oid': '{0}', 'ShortName': 'Ár', 'Value': '' + @PriceBruttoHUF + '' },", Guid.NewGuid().ToString());
                    _Result += string.Format("{ 'Oid': '{0}', 'ShortName': 'Érvényes (tól)', 'Value': '' + @ActualDate + '' },", Guid.NewGuid().ToString());
                    _Result += string.Format("{ 'Oid': '{0}', 'ShortName': 'Érvényes (ig)', 'Value': '' + @ExpirationDate + '' },", Guid.NewGuid().ToString());
                    _Result += string.Format("{ 'Oid': '{0}', 'ShortName': 'Akciós?', 'Value': '' + @IsAction + '' },", Guid.NewGuid().ToString());
                    _Result += string.Format("{ 'Oid': '{0}', 'ShortName': 'Árutasítás', 'Value': '' + @PricingCodeDescription + '' },", Guid.NewGuid().ToString());*/
                    _Result += "]";
                }
            }
            _Result= _Result.Replace("'", ((char)34).ToString());
            return _Result;
        }
        private string DX_GetStorageOutHeader_dxList(string database)
        {
            throw new NotImplementedException();
        }
        private bool DX_Login(string _UserName, string _Password, string database)
        {
            bool _Result=false;
            if (_session.IsConnected == true) { _session.Disconnect(); }
            _session.Connect();
            if (_session.IsConnected == true)
            {
                User _User = _session.FindObject<User>(CriteriaOperator.Parse("UserName=?", _UserName));
                if (_User != null)
                {
                    if (_User.ComparePassword(_Password) == true)
                    {
                        _Result = true;
                    }
                }
            }
            return _Result;
        }
        private string DX_GetCustomersFrom_dxSelectBox()
        {
            String _Result = "";
            if (_session.IsConnected == true) { _session.Disconnect(); }
            _session.Connect();
            if (_session.IsConnected == true)
            {
                XPCollection<CustomersFrom> _XPCollection_CustomersFrom=new XPCollection<CustomersFrom>(CriteriaOperator.Parse("1=1"));
                _XPCollection_CustomersFrom.Sorting.Add(new SortProperty("FullName",DevExpress.Xpo.DB.SortingDirection.Ascending));
                if (_XPCollection_CustomersFrom.Count>0)
                {
                    _Result = "[";
                    foreach (CustomersFrom _CustomersFrom in _XPCollection_CustomersFrom)
                    {
                        if (_Result == "[")
                        {
                            _Result += string.Format("'{0}'", _CustomersFrom.FullName);
                        }
                        else
                        {
                            _Result += string.Format(",'{0}'", _CustomersFrom.FullName);
                        }
                    }
                    _Result += "]";
                }
                else
                {
                    _Result = "['<NINCS>']";
                }
            }
            return _Result;
        }
    }
}
