using System;
using System.IO;
using Avalonia.Automation;
using Avalonia.Media;
using Avalonia.Media.Imaging;
using MarketData.CNNProcessing;
using MarketData.Utils;
using ScottPlot;
using SkiaSharp;

public static class TextMarkerImageGenerator
  {
    public static Image GenerateImage(String text,int width=130, int height=24, int fontSize=12)
    {
      ImageHelper imageHelper = new ImageHelper();
      imageHelper.CreateImage(width, height); 
      imageHelper.Fill(SKColors.White);
      SKTextAlign align = SKTextAlign.Center;
      SKFont font = new SKFont(SKTypeface.FromFamilyName("Arial",500,5,SKFontStyleSlant.Upright), fontSize);
      imageHelper.DrawLine(SKColors.Black,1, new SKPoint(0,0), new SKPoint(width-1,0)); // bottom left to right
      imageHelper.DrawLine(SKColors.Black,1, new SKPoint(width-1,0), new SKPoint(width-1,height-1)); // up lefthand side
      imageHelper.DrawLine(SKColors.Black,1, new SKPoint(0,height-1), new SKPoint(width-1,height-1)); // top left to right
      imageHelper.DrawLine(SKColors.Black,1, new SKPoint(0,height-1), new SKPoint(0,0)); // left hand side top to bottom
      imageHelper.DrawText(text, new SKPoint(width / 2, height-8), SKColors.Black, align, font);
      using MemoryStream memoryStream = new MemoryStream();
      imageHelper.ToStream().CopyTo(memoryStream);
      return new ScottPlot.Image(memoryStream.ToArray());
    }

    public static Image GenerateImage(String text,int fontSize=11)
    {
      ImageHelper imageHelper = new ImageHelper();
      SKFont font = default;
      if (Utility.IsOSWindows())font = new SKFont(SKTypeface.FromFamilyName("Helvetica",500,5,SKFontStyleSlant.Upright), fontSize);
      else font = new SKFont(SKTypeface.FromFamilyName(familyName: "Helvetica", weight: SKFontStyleWeight.Normal, width: SKFontStyleWidth.UltraCondensed, slant: SKFontStyleSlant.Upright), fontSize, .80f);
      SKTextAlign align = SKTextAlign.Left;
      imageHelper.CreateBoundedText(text, SKColors.Black, SKColors.White, align, font); 
      using MemoryStream memoryStream = new MemoryStream();
      imageHelper.ToStream().CopyTo(memoryStream);
      return new ScottPlot.Image(memoryStream.ToArray());
    }

    public static Image ToSPImage(IImage image)
    {
      Bitmap bitmap = (Bitmap)image;  //ImageCache.GetInstance().GetImage(ImageCache.ImageType.BlueTriangleUp);
      using MemoryStream memoryStream = new MemoryStream();
      bitmap.Save(memoryStream);
      return new ScottPlot.Image(memoryStream.ToArray());
    }

    public static IImage GenerateImage(int width, int height, SKColor color)
    {
      ImageHelper imageHelper = new ImageHelper();
      imageHelper.CreateImage(width, height);
      imageHelper.Fill(color);
      Avalonia.Media.Imaging.Bitmap avBitmap = new Avalonia.Media.Imaging.Bitmap(imageHelper.ToStream());
      return avBitmap;
    }
  }
