//  
//   Rebex Sample Code License
// 
//   Copyright 2026, REBEX CR s.r.o.
//   All rights reserved.
//   https://www.rebex.net/
// 
//   Permission to use, copy, modify, and/or distribute this software for any
//   purpose with or without fee is hereby granted.
// 
//   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
//   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
//   OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
//   NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
//   HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
//   WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
//   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
//   OTHER DEALINGS IN THE SOFTWARE.
// 

using System;
using System.Collections.Generic;
using System.Linq;

namespace Rebex.Samples
{
    /// <summary>
    /// Parses and holds command line options for <see cref="HttpDownloader"/>.
    /// </summary>
    public class HttpDownloaderOptions
    {
        public const string APP_USAGE =
            "HttpsGet [URL] [OPTION]...\n" +
            "-h                   Print this help\n" +
            "-O FILE              Write resource to FILE (relative or absolute path)\n" +
            "-q                   Quiet mode\n" +
            "-S                   Print server response\n" +
            "-spider              Only HEAD request (don't download resource)\n" +
            "-i FILE              Download resources specified in the FILE\n" +
            "-nocheckcertificate  Don't validate server certificate";

        private const string GENERAL_PARSER_ERROR = "Invalid options.";

        private const string HELP_OPTION = "-h";
        private const string OUTPUT_FILE_OPTION = "-O";
        private const string BE_QUIET_OPTION = "-q";
        private const string PRINT_SERVER_RESPONSE_OPTION = "-S";
        private const string SPIDER_MODE_OPTION = "-spider";
        private const string USER_AGENT_OPTION = "-U";
        private const string NO_CHECK_CERTIFICATE_OPTION = "-nocheckcertificate";
        private const string INPUT_FILE_WITH_URLS_OPTION = "-i";

        private HttpDownloaderOptions()
        {
        }

        public string Url { get; private set; }
        public string OutputFile { get; private set; }
        public bool QuietMode { get; private set; }
        public bool PrintServerResponse { get; private set; }
        public bool SpiderMode { get; private set; }
        public string UserAgent { get; private set; }
        public string InputFileWithUrlsPath { get; private set; }
        public bool ShowHelp { get; private set; }
        public bool NoCheckCertificate { get; private set; }

        public static HttpDownloaderOptions CreateFrom(string[] args)
        {
            try
            {
                if (args.Length < 1)
                {
                    return null;
                }

                var options = new HttpDownloaderOptions();

                options.Url = args[0].Trim();
                if (!options.Url.StartsWith("https:", StringComparison.OrdinalIgnoreCase))
                {
                    Console.WriteLine($"This sample supports HTTPS only. Invalid URL: {options.Url}\n");
                    return null;
                }

                for (int i = 1; i < args.Length; i++)
                {
                    var arg = args[i].Trim();
                    if (arg.Length == 0)
                        continue;

                    switch (arg)
                    {
                        case OUTPUT_FILE_OPTION:
                            options.OutputFile = TryGetOptionValue(args, ++i);
                            break;
                        case BE_QUIET_OPTION:
                            options.QuietMode = true;
                            break;
                        case PRINT_SERVER_RESPONSE_OPTION:
                            options.PrintServerResponse = true;
                            break;
                        case SPIDER_MODE_OPTION:
                            options.SpiderMode = true;
                            break;
                        case USER_AGENT_OPTION:
                            options.UserAgent = TryGetOptionValue(args, ++i);
                            break;
                        case INPUT_FILE_WITH_URLS_OPTION:
                            options.InputFileWithUrlsPath = TryGetOptionValue(args, ++i);
                            break;
                        case HELP_OPTION:
                            options.ShowHelp = true;
                            break;
                        case NO_CHECK_CERTIFICATE_OPTION:
                            options.NoCheckCertificate = true;
                            break;
                        default:
                            Console.WriteLine($"Invalid option: {arg}\n");
                            return null;
                    }
                }

                return options;
            }
            catch (Exception ex)
            {
                throw new OptionsParserException(GENERAL_PARSER_ERROR, ex);
            }
        }

        private static string TryGetOptionValue(string[] args, int index, string defaultOptionValue = "")
        {
            return (index < args.Length) ? args[index].Trim().Trim('\'', '"') : defaultOptionValue;
        }
    }
}
