using System;
using System.Collections.ObjectModel;
using System.IO;
using PatrickChatCtrlTemplate.Portable.Models;
using SkiaSharp;
using Telerik.XamarinForms.Common;
using Xamarin.Forms;

namespace PatrickChatCtrlTemplate.Portable.ViewModels
{
    public class MainPageViewModel : NotifyPropertyChangedBase
    {
        public MainPageViewModel()
        {
            // Both authors have a byte[] as the profile image source
            this.Me = new ExtendedAuthor
            {
                Name = "human",
                ProfileImageSource = ImageSource.FromStream(() => new MemoryStream(GenerateProfileImageBytes()))
            };

            this.Bot = new ExtendedAuthor
            {
                Name = "Bot",
                ProfileImageSource = ImageSource.FromStream(() => new MemoryStream(GenerateProfileImageBytes()))
            };

            this.Items = new ObservableCollection<SimpleChatItem>();

            // Simulate async data loading
            Device.StartTimer(TimeSpan.FromMilliseconds(500), () =>
            {
                this.Items.Add(new SimpleChatItem { Author = this.Bot, Text = "Hi." });
                this.Items.Add(new SimpleChatItem { Author = this.Bot, Text = "How can I help you?" });
                return false;
            });
        }

        public ExtendedAuthor Me { get; set; }

        public ExtendedAuthor Bot { get; set; }

        public ObservableCollection<SimpleChatItem> Items { get; set; }

        private byte[] GenerateProfileImageBytes()
        {
            using (var bmp = new SKBitmap(36, 36))
            {
                var rand = new Random();
                var r = (byte)rand.Next(0, byte.MaxValue);
                var g = (byte)rand.Next(0, byte.MaxValue);
                var b = (byte)rand.Next(0, byte.MaxValue);

                var color = new SKColor(r, g, b, 255);

                for (int i = 0; i < bmp.Width; i++)
                {
                    for (int j = 0; j < bmp.Height; j++)
                    {
                        bmp.SetPixel(i, j, color);
                    }
                }

                using (SKImage image = SKImage.FromPixels(bmp.PeekPixels()))
                {
                    var data = image.Encode(SKEncodedImageFormat.Png, 100);
                    return data.ToArray();
                }
            }
        }
    }
}
