using System;
using System.Drawing.Printing;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace GameCardGenerator
{
    public partial class FormMain : Form
    {
        public FormMain()
        {
            InitializeComponent();
        }

        private Bitmap createGameCard(string cost = "", string guid = null)
        {
            if (guid == null)
            {
                guid = Guid.NewGuid().ToString();
            }

            return GameCards.Create(pictureBox.Width, pictureBox.Height,
                textTitle.Text, cost, guid,
                fontTitle.Color, fontCost.Color, fontGuid.Color, colorQR.Color,
                fontTitle.Font, fontCost.Font, fontGuid.Font,
                comboQREccLevel.SelectedIndex, (int)numQRPPM.Value);
        }

        Dictionary<string, int> cards = new Dictionary<string, int>();

        private void addCardsToDictionary()
        {
            cards = new Dictionary<string, int>();

            foreach (DataGridViewRow row in dataGridView.Rows)
            {
                if (row.IsNewRow) continue;

                string miktar = row.Cells[0].Value.ToString();
                int adet = int.Parse(row.Cells[1].Value.ToString());

                cards[miktar] = adet;
            }
        }

        private Bitmap createNextCard()
        {
            if (cards.Count > 0)
            {
                string key = cards.First().Key;

                if (cards[key] > 0)
                {
                    cards[key]--; if (cards[key] == 0) { cards.Remove(key); }
                    return createGameCard(key.ToString());
                }
                else
                {
                    cards.Remove(key);
                    return createNextCard();
                }
            }
            else
            {
                return null;
            }
        }

        private void FormMain_Load(object sender, EventArgs e)
        {
            textGuid.Text = Guid.NewGuid().ToString();
            comboQREccLevel.SelectedIndex = 3;
            dataGridView.Rows.Add();
            dataGridView.Rows[0].Cells[0].Value = "1";
            dataGridView.Rows[0].Cells[1].Value = "8";
            dataGridView.Rows.Add();
            dataGridView.Rows[1].Cells[0].Value = "5";
            dataGridView.Rows[1].Cells[1].Value = "8";
        }

        private void btnRandomGuid_Click(object sender, EventArgs e)
        {
            textGuid.Text = Guid.NewGuid().ToString();
        }

        private void btnGenerate_Click(object sender, EventArgs e)
        {
            Bitmap bitmap = createGameCard(textCost.Text, textGuid.Text);

            pictureBox.Image = bitmap;

            if (checkGenerateGuid.Checked) { textGuid.Text = Guid.NewGuid().ToString(); }

            if (checkCopy.Checked) { Clipboard.SetImage(bitmap); }
        }

        private void btnTitleFont_Click(object sender, EventArgs e)
        {
            fontTitle.ShowDialog();
        }

        private void btnCostFont_Click(object sender, EventArgs e)
        {
            fontCost.ShowDialog();
        }

        private void btnGuidFont_Click(object sender, EventArgs e)
        {
            fontGuid.ShowDialog();
        }

        private void btnQRColor_Click(object sender, EventArgs e)
        {
            colorQR.ShowDialog();
        }

        private void btnCopyImage_Click(object sender, EventArgs e)
        {
            if (pictureBox.Image != null)
            {
                Clipboard.SetImage(pictureBox.Image);
            }
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            PrintDocument printDocument = new PrintDocument();
            printDocument.DocumentName = "Game Card Generator";
            printDocument.DefaultPageSettings.Margins = new Margins(30, 30, 30, 30);

            addCardsToDictionary();

            printDocument.PrintPage += (object s, PrintPageEventArgs ev) =>
            {
                Graphics g = ev.Graphics;
                int w = ev.MarginBounds.Width;
                int h = ev.MarginBounds.Height;
                int x = ev.MarginBounds.X;
                int y = ev.MarginBounds.Y;

                Bitmap bitmap = createGameCard("1");
                float new_width = w / 2 - 15;
                float new_height = bitmap.Height * ((w / 2.0f) / bitmap.Width);
                float v_margin = (h - 4 * new_height) / 4;

                for (int i = 0; i < 4; i++)
                {
                    bitmap = createNextCard();

                    if (bitmap != null)
                    {
                        g.DrawImage(bitmap, x, y + i * new_height + v_margin * i, new_width, new_height);
                    }
                }

                for (int i = 0; i < 4; i++)
                {
                    bitmap = createNextCard();

                    if (bitmap != null)
                    {
                        g.DrawImage(bitmap, w / 2 + 45, y + i * new_height + v_margin * i, new_width, new_height);
                    }
                }

                ev.HasMorePages = cards.Count > 0;
            };

            PrintDialog printDialog = new PrintDialog();
            printDialog.Document = printDocument;

            if (printDialog.ShowDialog() == DialogResult.OK)
            {
                printDocument.Print();
            }
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Title = "Dışarı Aktar";
            sfd.Filter = "JPEG Resmi (*.jpg)|*.jpg|PNG Resmi (*.png)|*.png";
            sfd.FileName = "game-card";

            if (sfd.ShowDialog() == DialogResult.OK)
            {
                string fileName = sfd.FileName;
                string tmpName = "";
                Bitmap bitmap;
                int num = 1;

                addCardsToDictionary();

                while ((bitmap = createNextCard()) != null)
                {
                    tmpName = fileName.Replace(".", string.Format("-{0:D2}", num) + ".");

                    if (checkExportSquare.Checked)
                    {
                        int square = Math.Max(bitmap.Width, bitmap.Height);
                        using (Bitmap squareBitmap = new Bitmap(square, square))
                        {
                            Graphics g = Graphics.FromImage(squareBitmap);
                            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                            g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                            g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
                            g.Clear(Color.White);
                            g.DrawImage(bitmap, 
                                squareBitmap.Width / 2 - bitmap.Width / 2, 
                                squareBitmap.Height / 2 - bitmap.Height / 2);
                            bitmap = (Bitmap)squareBitmap.Clone();
                        }
                    }

                    bitmap.Save(tmpName , System.Drawing.Imaging.ImageFormat.Jpeg);
                    num++;
                }

                MessageBox.Show(num + " adet resim kaydedildi.");
            }
        }
    }
}