//  
//   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.IO;
using System.Windows.Forms;

using Rebex.Security;

namespace Rebex.Samples
{
    public partial class Form1 : Form
    {
        // encrypted file extension
        private const string EncryptionExtension = ".enc";

        // specifies operations to perform
        private enum Operation { Encrypt, Decrypt };

        public Form1()
        {
            InitializeComponent();
        }

        /// <summary>
        /// Handles source file path changes.
        /// </summary>
        private void txtSourceFile_TextChanged(object sender, EventArgs e)
        {
            // determine path of the output file
            string filePath = txtSourceFile.Text;
            string extension = Path.GetExtension(filePath);
            if (extension.Equals(EncryptionExtension, StringComparison.OrdinalIgnoreCase))
            {
                string dir = Path.GetDirectoryName(filePath);
                string destinationFileName = Path.GetFileNameWithoutExtension(filePath);
                txtDestinationFile.Text = Path.Combine(dir, destinationFileName);
            }
            else
            {
                txtDestinationFile.Text = filePath + EncryptionExtension;
            }
        }

        /// <summary>
        /// Handles '...' button click.
        /// </summary>
        private void btnOpen_Click(object sender, EventArgs e)
        {
            if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                txtSourceFile.Text = openFileDialog.FileName;
        }

        /// <summary>
        /// Handles 'Encrypt' button click.
        /// </summary>
        private void btnEncrypt_Click(object sender, EventArgs e)
        {
            PerformOperation(Operation.Encrypt);
        }

        /// <summary>
        /// Handles 'Decrypt' button click.
        /// </summary>
        private void btnDecrypt_Click(object sender, EventArgs e)
        {
            PerformOperation(Operation.Decrypt);
        }

        /// <summary>
        /// Encrypts or decrypts specified file.
        /// </summary>
        /// <param name="operation">Operation to perform.</param>
        private void PerformOperation(Operation operation)
        {
            // check input values
            if (string.IsNullOrEmpty(txtSourceFile.Text))
            {
                ShowError("Select source file.", "File not set");
                return;
            }

            if (string.IsNullOrEmpty(txtPassword.Text))
            {
                ShowError("Password must be set.", "Password not set");
                return;
            }

            if (!File.Exists(txtSourceFile.Text))
            {
                ShowError("Source file not found.", "File not found");
                return;
            }

            if (File.Exists(txtDestinationFile.Text) && !cbxOverwriteFile.Checked)
            {
                ShowError("Destination file already exists.\n" +
                    "Check the 'Overwrite existing file' checkbox to overwrite it.", "Destination file exists");
                return;
            }

            // perform operation
            FileEncryption encryptor = new FileEncryption();
            encryptor.OverwriteExistingFile = cbxOverwriteFile.Checked;
            encryptor.SetPassword(txtPassword.Text);

            try
            {
                if (operation == Operation.Encrypt)
                    encryptor.Encrypt(txtSourceFile.Text, txtDestinationFile.Text);
                else
                    encryptor.Decrypt(txtSourceFile.Text, txtDestinationFile.Text);

                ShowInfo("Operation finished successfully.", "Operation done");
            }
            catch (Exception ex)
            {
                ShowError(ex.ToString(), "Error occurred");
            }
        }

        /// <summary>
        /// Shows error message.
        /// </summary>
        /// <param name="message">Message to show.</param>
        /// <param name="caption">Window caption.</param>
        private void ShowError(string message, string caption)
        {
            MessageBox.Show(message, caption, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        }

        /// <summary>
        /// Shows information message.
        /// </summary>
        /// <param name="message">Message to show.</param>
        /// <param name="caption">Window caption.</param>
        private void ShowInfo(string message, string caption)
        {
            MessageBox.Show(message, caption, MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    }
}
