using DeskRedis.Exceptions;
using DeskRedis.Util;
using ServiceStack.Redis;
using System;
using System.Windows;

namespace DeskRedis
{
    /// <summary>
    /// WinRenameKey.xaml 的交互逻辑
    /// </summary>
    public partial class WinRenameKey : Window
    {
        #region 私有变量
        /// <summary>
        /// 配置id。
        /// </summary>
        private readonly string configId;
        /// <summary>
        /// 数据库索引。
        /// </summary>
        private readonly int index;
        /// <summary>
        /// 键
        /// </summary>
        private readonly string key;
        #endregion


        #region 委托、事件
        /// <summary>
        /// 当重命名完成时发生。
        /// </summary>
        public event Action<string> OnUpdatedKey;
        #endregion


        #region 构造方法
        /// <summary>
        /// 使用指定的参数创建实例。
        /// </summary>
        /// <param name="configId">配置id</param>
        /// <param name="index">数据库索引</param>
        /// <param name="key">键</param>
        public WinRenameKey(string configId, int index, string key)
        {
            this.InitializeComponent();
            this.WindowStartupLocation = WindowStartupLocation.CenterScreen;

            this.configId = configId;
            this.index = index;
            this.key = key;
            this.tblockKey.Text = key;
        }
        #endregion


        /// <summary>
        /// 当鼠标点击修改按钮时发生。
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnUpdate_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                AssertUtil.FormDataValidate("请输入合法的键。", () => { return string.IsNullOrWhiteSpace(this.tbNewKey.Text.Trim()); });

                if (GlobalBusiness.RedisCaches[this.configId].Get(this.tbNewKey.Text.Trim(), this.index) != null)
                {
                    MessageBox.Show("已存在键。");
                    return;
                }
                GlobalBusiness.RedisCaches[this.configId].RenameKey(this.key, this.tbNewKey.Text.Trim(), this.index);
                this.OnUpdatedKey?.Invoke(this.tbNewKey.Text.Trim());

                this.Close();
            }
            catch (IllegalFormDataException ex)
            {
                MessageBox.Show(ex.Message);
            }
            catch (RedisException ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// 当鼠标点击关闭按钮时发生。
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnClose_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }
    }
}