using System;
using System.IO;
using System.Threading;
using Microsoft.AspNetCore.DataProtection;

namespace ConfiguredDataProtection_final {
    public class Program {
        public static void Main(string[] args) {

            // Configure key folder
            var keyFolder = Path.Combine(Directory.GetCurrentDirectory(), "Keys");
            Console.WriteLine($"Program key folder: {keyFolder}");

            // Create instance of regular protector
            var provider = DataProtectionProvider.Create(new DirectoryInfo(keyFolder), cfg => {
                cfg.SetApplicationName("MyApp");
                cfg.ProtectKeysWithDpapi();
            });
            var protector = provider.CreateProtector("My Purpose String");

            // Convert it to timed protector
            var timedProtector = protector.ToTimeLimitedDataProtector();

            // Get data to protect
            Console.Write("Enter data to protect: ");
            var input = Console.ReadLine();

            // Protect them
            var protectedString = timedProtector.Protect(input, TimeSpan.FromSeconds(5));
            Console.WriteLine($"[{DateTime.Now}] Protected data: {protectedString}");

            // Repeatedly try to unprotect data
            try {
                while (true) {
                    var unprotectedString = timedProtector.Unprotect(protectedString);
                    Console.WriteLine($"[{DateTime.Now}] Unprotected data: {unprotectedString}");
                    Thread.Sleep(1000); // Wait for 1 s
                }
            }
            catch (Exception ex) {
                Console.WriteLine("Failed to unprotect data");
                Console.WriteLine(ex.Message);
            }

        }
    }
}
