using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.IO;
using System.Drawing;
using static NeuralNetwork.PictureWork.PictureWork;
using NeuralNetwork.Model.Neutral.CNTK;

namespace NeuralNetwork.Model.Services
{
    /// <summary>
    /// Тестовая заглушка сервиса
    /// </summary>
    public class TextRecognisingTestService : ITextRecognisingService
    {
        public bool TryOpen(byte[] image)
        {
            Bitmap bitmap = null;

            try
            {
                using (MemoryStream stream = new MemoryStream(image))
                {
                    bitmap = new Bitmap(stream);
                }
            }
            catch (Exception)
            {
                return false;
            }

            return true;            
        }

        public int Work(byte[] image)
        {
            Bitmap bitmap = null;
            try
            {
                using (MemoryStream stream = new MemoryStream(image))
                {
                    bitmap = new Bitmap(stream);
                }
            }
            catch
            {
                
            }

            if (bitmap != null)
            {
                bitmap = RemoveTransparency(bitmap);
                var collect = FindObjects(BitmapToFloatMatrixRgbQ(bitmap));
                if (collect.Length == 1)
                {
                    var floatArray = BitmapToFloatArrayRgbQ(InsertBitmap(new Bitmap(bitmap.Clone(collect.First(), bitmap.PixelFormat), new Size(20, 20)), 28, 28));
                    //var byteList = floatArray.Select(e => (byte)Math.Round(e * 256f)).ToList();
                    //using (StreamWriter wr = new StreamWriter(@"D:\dataset.csv", true))
                    //{
                    //    wr.Write("0");
                    //    byteList.ForEach(e => wr.Write("," + e));
                    //    wr.WriteLine();
                    //}
                    var res = MNIST.GetNumber(floatArray);
                    return res;
                }
            }

            return -1;
        }
    }
}
