using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Text;
using System.Web;

namespace ynhtm.API
{
    using Common;

    public class Authcode : BaseHandler
    {
        const int WIDTH = 80;
        const int HEIGHT = 26;
        const float FONTSIZE = 20f;
        const int CHARCOUNT = 4;
        static readonly Random RAND;

        static Authcode()
        {
            RAND = new Random(~unchecked((int)DateTime.Now.Ticks));
        }
        public override void Process()
        {
            var request = this.Request;
            var response = this.Response;
            response.Clear();
            response.Cache.SetCacheability(HttpCacheability.NoCache);
            response.Cache.SetNoStore();
            var code = "";
            for (var i = 0; i < CHARCOUNT; i++)
            {
                code += RAND.Next(1, 10).ToString();
            }
            this.Session[BLL.Setting.AUTHCODEKEY] = code;
            response.Buffer = true;
            response.ContentType = "image/jpeg";
            response.Charset = null;

            using (var font = new Font("Arial Black", FONTSIZE, GraphicsUnit.Pixel))
            {
                using (var bmp = new Bitmap(WIDTH, HEIGHT))
                {
                    using (var g = Graphics.FromImage(bmp))
                    {
                        g.Clear(Color.White);
                        g.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
                        g.CompositingQuality = CompositingQuality.HighQuality;
                        g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                        var s = g.MeasureString(code, font);
                        var j = WIDTH / CHARCOUNT;
                        var y = HEIGHT / 2f;
                        var k = -j / 2f;
                        var u = -s.Height / 2f;
                        for (var i = 0; i < CHARCOUNT; i++)
                        {
                            var x = j / 2f + j * i;
                            g.TranslateTransform(x, y);
                            g.RotateTransform(RAND.Next(-20, 20));
                            g.DrawString(code[i].ToString(), font, Brushes.Black, k, u);
                            g.ResetTransform();
                        }
                        var d = WIDTH * HEIGHT / 20;
                        for (var i = 0; i < d; i++) g.FillRectangle(Brushes.Black, RAND.Next(0, WIDTH - 1), RAND.Next(0, HEIGHT - 1), 1, 1);
                        bmp.SaveJpeg(80L, response.OutputStream);
                    }
                }
            }
            response.End();
        }
    }
}