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));
                    int res = -2;
                    return res;
                }
            }

            return -1;
        }

        public int Learn(byte[] image, int number)
        {
            Bitmap bitmap = null;
            try
            {
                using (MemoryStream stream = new MemoryStream(image))
                {
                    bitmap = new Bitmap(stream);
                }
                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));
                        MNIST.WriteNumber(floatArray, number);
                        return -2;
                    }
                }
            }
            catch
            {

            }
            return -1;
        }
    }
}
