﻿using System;
using System.Net.Http;
using Vstack.Common.Extensions;
using Vstack.Services.General;
using Vstack.Services.Services;

namespace Vstack.Api.Web.Controllers
{
    public abstract class DtoController2<TDtoService, TPermissions>
        : RestfulController
        where TDtoService : BaseDtoService2<TPermissions>
        where TPermissions : RestPermissions
    {
        private const string Include = nameof(Include);
        private readonly TDtoService _dtoService;
        private bool permissionsSet = false;

        protected DtoController2(TDtoService dtoService)
        {
            this._dtoService = dtoService;
        }

        public abstract TPermissions Permissions { get; }

        protected virtual TDtoService DtoService
        {
            get
            {
                if (this.permissionsSet == false)
                {
                    this._dtoService.Permissions = this.Permissions;
                    this._dtoService.Includes = this.GetIncludes();
                    this.permissionsSet = true;
                }

                return this._dtoService;
            }
        }

        private string[] GetIncludes()
        {
            return (this.Request.GetQueryNameValuePairs().GetQueryStringValue(Include) ?? string.Empty).Split(",", StringSplitOptions.RemoveEmptyEntries);
        }
    }
}