﻿using EA.Addins.DiscussionsBackup.Common;
using System.Windows.Forms;

namespace EA.Addins.DiscussionsBackup.Commands
{
    public class BackupCommand : IEaMenuCommand
    {
        public Result<string> Execute(Repository repository)
        {
            if (null == repository)
                return Result.Fail<string>(TextResources.RepositoryNotSet);
            var fileName = GetSaveFileName();            
            if (string.IsNullOrWhiteSpace(fileName))
                return Result.Fail<string>(" ");
            var discussionsXml = GetDiscussionsXml(repository);
            SaveToFile(fileName, discussionsXml);

            var msg = string.Format(TextResources.BackupCreatedFormatted, fileName);
            return Result.Ok(msg);
        }

        protected virtual void SaveToFile(string fileName, string discussionsXml)
        {
            System.IO.File.WriteAllText(fileName, discussionsXml);
        }

        protected virtual string GetDiscussionsXml(Repository repository)
        {           
            return repository.SQLQuery("select * from t_document where ElementType='Post'");
        }
        
        protected virtual string GetSaveFileName()
        {
            using (var saveDialog = new SaveFileDialog())
            {
                saveDialog.DefaultExt = ".xml";
                saveDialog.Title = TextResources.SaveDialogTitleBackup;
                saveDialog.Filter = TextResources.XmlFilesFilter;
                saveDialog.CheckPathExists = true;
                                
                if (saveDialog.ShowDialog() != DialogResult.OK)
                    return string.Empty;
                return saveDialog.FileName;
            }
        }
    }
}
