//  
//   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.ComponentModel;
using System.IO;
using Microsoft.Win32;
using Rebex.Security;

namespace Rebex.Samples
{
    /// <summary>
    /// ViewModel for MainWindow class.
    /// </summary>
    /// <remarks>
    /// Please note that using dialogs such as MessageBox and OpenFileDialog in this class
    /// is not considered as clean MVVM pattern.
    /// </remarks>
    public class MainWindowViewModel : INotifyPropertyChanged
    {
        // encrypted file extension
        private const string EncryptionExtension = ".enc";

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

        private string _sourceFilePath;
        private string _destinationFilePath;
        private string _password;

        /// <summary>
        /// Gets or sets destination path.
        /// </summary>
        public string DestinationFilePath
        {
            get { return _destinationFilePath; }
            set
            {
                if (_destinationFilePath != value)
                {
                    _destinationFilePath = value;

                    // make this property "observable" by binding engine of WPF
                    OnPropertyChanged("DestinationFilePath");
                }
            }
        }

        /// <summary>
        /// Gets or sets source path.
        /// </summary>
        public string SourceFilePath
        {
            get { return _sourceFilePath; }
            set
            {
                if (_sourceFilePath != value)
                {
                    _sourceFilePath = value;
                    SetDestinationFilePath(value);

                    // make this property "observable" by binding engine of WPF
                    EncryptCommand.RaiseCanExecuteChanged();
                    DecryptCommand.RaiseCanExecuteChanged();
                    OnPropertyChanged("SourceFilePath");
                }
            }
        }

        /// <summary>
        /// Gets or sets the password.
        /// </summary>
        public string Password
        {
            get { return _password; }
            set
            {
                _password = value;

                // notify the commands if this property changes
                EncryptCommand.RaiseCanExecuteChanged();
                DecryptCommand.RaiseCanExecuteChanged();
            }
        }

        /// <summary>
        /// Gets or sets value indicating whether the destination file can be overwritten.
        /// </summary>
        public bool OverwriteExistingFiles { get; set; }

        /// <summary>
        /// This Command handles Encrypt button.
        /// </summary>
        public SimpleCommand EncryptCommand { get; private set; }

        public SimpleCommand DecryptCommand { get; private set; }

        public SimpleCommand OpenCommand { get; private set; }

        public MainWindowViewModel()
        {
            // initialize commands for buttons
            EncryptCommand = new SimpleCommand(Encrypt, CanExecuteOperation);
            DecryptCommand = new SimpleCommand(Decrypt, CanExecuteOperation);
            OpenCommand = new SimpleCommand(Open);
        }

        private bool CanExecuteOperation()
        {
            return !string.IsNullOrEmpty(SourceFilePath) && !string.IsNullOrEmpty(Password);
        }

        /// <summary>
        /// EncryptCommand execute method.
        /// </summary>
        private void Encrypt()
        {
            PerformOperation(Operation.Encrypt);
        }

        /// <summary>
        /// DecryptCommand execute method.
        /// </summary>
        private void Decrypt()
        {
            PerformOperation(Operation.Decrypt);
        }

        /// <summary>
        /// Encrypts or decrypts specified file.
        /// </summary>
        /// <param name="operation">Operation to perform.</param>
        private void PerformOperation(Operation operation)
        {
            // check destination file existence
            if (!OverwriteExistingFiles && File.Exists(DestinationFilePath))
            {
                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 = OverwriteExistingFiles;
            encryptor.SetPassword(Password);

            try
            {
                if (operation == Operation.Encrypt)
                    encryptor.Encrypt(SourceFilePath, DestinationFilePath);
                else
                    encryptor.Decrypt(SourceFilePath, DestinationFilePath);

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

        /// <summary>
        /// OpenCommand execute method.
        /// </summary>
        private void Open()
        {
            OpenFileDialog openDialog = new OpenFileDialog();
            openDialog.Filter = "Encrypted files|*.enc|All files|*.*";
            openDialog.FilterIndex = 2;

            if (openDialog.ShowDialog().GetValueOrDefault(false))
            {
                SourceFilePath = openDialog.FileName;
            }
        }

        private void SetDestinationFilePath(string fileName)
        {
            if (Path.GetExtension(fileName) == EncryptionExtension)
            {
                string dir = Path.GetDirectoryName(fileName);
                string destinationFileName = Path.GetFileNameWithoutExtension(fileName);
                DestinationFilePath = Path.Combine(dir, destinationFileName);
            }
            else
            {
                DestinationFilePath = fileName + EncryptionExtension;
            }
        }

        /// <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)
        {
            System.Windows.MessageBox.Show(message, caption, System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.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)
        {
            System.Windows.MessageBox.Show(message, caption, System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Information);
        }

        #region property changed

        public event PropertyChangedEventHandler PropertyChanged;

        private void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }

        #endregion
    }
}
