using QRCoder;
using System;
using System.Drawing;
using System.Web.Http;
using System.Drawing.Printing;
using System.Drawing.Imaging;
using System.IO;
using LHDN.CRM.Models.ViewModels;
using LHDN.CRM.WebAPI.Filters;
using Newtonsoft.Json;
using LHDN.CRM.BC.Services;

namespace LHDN.CRM.WebAPI.Controllers.Api
{
    public class QRCodeApiController : BaseApiController
    {
        private byte[] imageBytes;
        private EncoderParameter myEncoderParameter;
        private EncoderParameters myEncoderParameters;

        public QRCodeApiController()
        {
            imageBytes = null;
        }

        [HttpPost]
        [ApiErrorHandler]
        public IHttpActionResult GenQRCode(QRCodeViewModel vm)
        {
            QRCodeGenerator qrGenerator = new QRCodeGenerator();

            var json = JsonConvert.SerializeObject(vm);

            var _ecclevel = AdminService.QRECCLevel;

            QRCodeGenerator.ECCLevel ECCLevel = QRCodeGenerator.ECCLevel.Q;

            switch (_ecclevel)
            {
                case "L":
                    ECCLevel = QRCodeGenerator.ECCLevel.L;
                    break;
                case "M":
                    ECCLevel = QRCodeGenerator.ECCLevel.M;
                    break;
                case "H":
                    ECCLevel = QRCodeGenerator.ECCLevel.H;
                    break;
            }

            //QRCodeData qrCodeData = qrGenerator.CreateQrCode(json, ECCLevel);
            //Base64QRCode qrCode = new Base64QRCode(qrCodeData);
            //string qrCodeImageAsBase64 = qrCode.GetGraphic(20);

            //qrCodeData.Dispose();
            //qrCode.Dispose();
            string qrCodeImageAsBase64 = string.Empty;

            using (QRCodeData qrCodeData = qrGenerator.CreateQrCode(json, ECCLevel))
            {
                using (Base64QRCode qrCode = new Base64QRCode(qrCodeData))
                {
                    qrCodeImageAsBase64 = qrCode.GetGraphic(20);
                }
            }

            return Json(qrCodeImageAsBase64);
        }
    }
}