using ManagementSample.Models;
using System;
using System.Collections.Generic;
using System.Web.Mvc;
using LicenseSpring;
using System.Linq;

namespace ManagementSample.Controllers
{
    public class HomeController : Controller
    {
        private ManagementService service;

        public ActionResult Index()
        {
            HomeViewModel model = new HomeViewModel();
            try
            {
                Initialise();
                model.message = "Generating keys." + System.Environment.NewLine;
                string productCode = "DP";
                // Generate 2 license keys
                var licenseKeys = GenerateLicenseKey( productCode, 2 );
                foreach( var key in licenseKeys )
                    model.message += key + System.Environment.NewLine;

                // Create customer and licenses
                Customer customer = new Customer()
                {
                    CompanyName = "TestCompany",
                    Email = "someone@test.com"
                };
                var license1 = new LicenseDetails();
                license1.LicenseKey = licenseKeys.First();
                license1.EnableMaintenancePeriod = true;
                license1.MaintenanceEndDate = DateTime.Now.AddMonths( 3 ).ToString( "yyyy-MM-dd" );
                var license2 = new LicenseDetails
                {
                    LicenseKey = licenseKeys.Last(),
                    EnableMaintenancePeriod = true,
                    MaintenanceDuration = "7m", // 7 months
                    Type = LicenseType.TimeLimited,
                    ValidityDuration = "14m"
                };

                var licenses = new List<LicenseDetails>
                {
                    license1,
                    license2
                };

                var orderInfo = new Order( customer );
                // Order 2 licenses
                var orderID = CreateOrder( licenses.ToArray(), productCode, orderInfo );

                // Append one more license to existing order
                licenseKeys = GenerateLicenseKey( productCode );
                var license3 = new LicenseDetails
                {
                    LicenseKey = licenseKeys.Last(),
                    Type = LicenseType.Consumption,
                    MaxConsumptions = 100,
                    AllowOverages = true,
                    MaxOverages = 50,
                    ResetConsumption = true,
                    ConsumptionPeriod = "week"
                };
                model.message += "Generating key." + System.Environment.NewLine;
                model.message += licenseKeys.Last() + System.Environment.NewLine;
                licenses.Clear();
                licenses.Add( license3 );
                orderInfo = new Order( orderID, customer );
                orderID = CreateOrder( licenses.ToArray(), productCode, orderInfo );
                model.message += "Order was created successfully." + System.Environment.NewLine;
                model.message += "Order ID: " + orderID + System.Environment.NewLine;

                var Id = GetOrder( orderID ).Id;

                model.message += "Getting managers for order " + Id + System.Environment.NewLine;
                var managers = ListManagersOnOrder( Id );
                if( managers != null )
                {
                    foreach( var user in managers )
                        model.message += "Managers email: " + user.Email + System.Environment.NewLine;
                }
                model.message += "Getting licenses for order " + Id + System.Environment.NewLine;

                foreach( var orderItem in GetOrderLicenses( Id ) )
                    model.message += "License key: " + orderItem.Key() + System.Environment.NewLine;
            }
            catch( Exception ex )
            {
                model.message += ex.Message + System.Environment.NewLine;
            }
            return View( model );
        }

        private void Initialise()
        {
            var configuration = LSConfig.CreateManagementConfiguration();
            service = new ManagementService( configuration );
        }
        private string[] GenerateLicenseKey( string productCode, uint quantity = 1 )
        {
            return service.LicenseService.GenerateLicenseKey( productCode, quantity );
        }

        private string CreateOrder( LicenseDetails[] licenses, string productCode, Order orderInfo )
        {
            return service.OrderService.CreateOrder( licenses, productCode, orderInfo );
        }


        private Order GetOrder( string storeId )
        {
            uint count;
            ListOrdersRequestDto dto = new ListOrdersRequestDto()
            {
                ClientOrderId = storeId
            };
            var rez = service.OrderService.ListOrders( dto, out count );

            return rez != null && rez.Length == 1 ? rez[0] : null;
        }
        private License[] GetOrderLicenses( ulong orderId )
        {
            return service.OrderService.ListOrderLicenses( orderId );
        }

        private LicenseUser[] ListManagersOnOrder( ulong orderId )
        {
            return service.OrderService.ListManagersOnOrder( orderId );
        }

    }
}