using System.Linq;
using System.Threading.Tasks;
using Jellyfin.Api.Constants;
using Jellyfin.Api.Models.StartupDtos;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Library;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace Jellyfin.Api.Controllers
{
    /// 
    /// The startup wizard controller.
    /// 
    [Authorize(Policy = Policies.FirstTimeSetupOrElevated)]
    public class StartupController : BaseJellyfinApiController
    {
        private readonly IServerConfigurationManager _config;
        private readonly IUserManager _userManager;
        /// 
        /// Initializes a new instance of the  class.
        /// 
        /// The server configuration manager.
        /// The user manager.
        public StartupController(IServerConfigurationManager config, IUserManager userManager)
        {
            _config = config;
            _userManager = userManager;
        }
        /// 
        /// Completes the startup wizard.
        /// 
        /// Startup wizard completed.
        /// A  indicating success.
        [HttpPost("Complete")]
        [ProducesResponseType(StatusCodes.Status204NoContent)]
        public ActionResult CompleteWizard()
        {
            _config.Configuration.IsStartupWizardCompleted = true;
            _config.SetOptimalValues();
            _config.SaveConfiguration();
            return NoContent();
        }
        /// 
        /// Gets the initial startup wizard configuration.
        /// 
        /// Initial startup wizard configuration retrieved.
        /// An  containing the initial startup wizard configuration.
        [HttpGet("Configuration")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        public ActionResult GetStartupConfiguration()
        {
            var result = new StartupConfigurationDto
            {
                UICulture = _config.Configuration.UICulture,
                MetadataCountryCode = _config.Configuration.MetadataCountryCode,
                PreferredMetadataLanguage = _config.Configuration.PreferredMetadataLanguage
            };
            return result;
        }
        /// 
        /// Sets the initial startup wizard configuration.
        /// 
        /// The UI language culture.
        /// The metadata country code.
        /// The preferred language for metadata.
        /// Configuration saved.
        /// A  indicating success.
        [HttpPost("Configuration")]
        [ProducesResponseType(StatusCodes.Status204NoContent)]
        public ActionResult UpdateInitialConfiguration(
            [FromForm] string uiCulture,
            [FromForm] string metadataCountryCode,
            [FromForm] string preferredMetadataLanguage)
        {
            _config.Configuration.UICulture = uiCulture;
            _config.Configuration.MetadataCountryCode = metadataCountryCode;
            _config.Configuration.PreferredMetadataLanguage = preferredMetadataLanguage;
            _config.SaveConfiguration();
            return NoContent();
        }
        /// 
        /// Sets remote access and UPnP.
        /// 
        /// Enable remote access.
        /// Enable UPnP.
        /// Configuration saved.
        /// A  indicating success.
        [HttpPost("RemoteAccess")]
        [ProducesResponseType(StatusCodes.Status204NoContent)]
        public ActionResult SetRemoteAccess([FromForm] bool enableRemoteAccess, [FromForm] bool enableAutomaticPortMapping)
        {
            _config.Configuration.EnableRemoteAccess = enableRemoteAccess;
            _config.Configuration.EnableUPnP = enableAutomaticPortMapping;
            _config.SaveConfiguration();
            return NoContent();
        }
        /// 
        /// Gets the first user.
        /// 
        /// Initial user retrieved.
        /// The first user.
        [HttpGet("User")]
        [HttpGet("FirstUser")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        public ActionResult GetFirstUser()
        {
            // TODO: Remove this method when startup wizard no longer requires an existing user.
            _userManager.Initialize();
            var user = _userManager.Users.First();
            return new StartupUserDto
            {
                Name = user.Username,
                Password = user.Password
            };
        }
        /// 
        /// Sets the user name and password.
        /// 
        /// The DTO containing username and password.
        /// Updated user name and password.
        /// 
        /// A  that represents the asynchronous update operation.
        /// The task result contains a  indicating success.
        /// 
        [HttpPost("User")]
        [ProducesResponseType(StatusCodes.Status204NoContent)]
        public async Task UpdateUser([FromForm] StartupUserDto startupUserDto)
        {
            var user = _userManager.Users.First();
            user.Username = startupUserDto.Name;
            await _userManager.UpdateUserAsync(user).ConfigureAwait(false);
            if (!string.IsNullOrEmpty(startupUserDto.Password))
            {
                await _userManager.ChangePassword(user, startupUserDto.Password).ConfigureAwait(false);
            }
            return NoContent();
        }
    }
}