using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;

namespace Baza_Reklam.Classes.Helpers
{
    public class PdfHelper
    {
        private readonly string _reklama;
        private string _errorMessage;

        public PdfHelper(string reklama)
        {
            _reklama = reklama.Trim().ToUpper();
        }

        public string ErrorMessage
        {
            get { return _errorMessage; }
        }

        public bool DisplayPdf()
        {
            string url = ConfigurationHelper.GetSettingByKey("Application.Pdf.Date") ??
             "http://truck.pl/ogloszenia/_getFile.asp?pdfdate,{0},,";
            url = string.Format(url, _reklama);

            string pdfDate = WebRequestHelper.GetResponse(url);

            DateTime pdfDateTime;

            if (!DateTime.TryParse(pdfDate, null, DateTimeStyles.None, out pdfDateTime))
            {
                //MessageBox.Show("Nie znaleziono pliku PDF dla wybranej reklamy");
                _errorMessage = "Nie znaleziono pliku PDF dla wybranej reklamy";
                return false;
            }

            string pdfDirectory = Environment.CurrentDirectory + Path.DirectorySeparatorChar + "pdf";
            string pdfFile = Environment.CurrentDirectory + Path.DirectorySeparatorChar + "pdf" +
                             Path.DirectorySeparatorChar + _reklama + ".pdf";

            if (!Directory.Exists(pdfDirectory))
                Directory.CreateDirectory(pdfDirectory);

            string pdfUrl = ConfigurationHelper.GetSettingByKey("Application.Pdf.File") ??
                            "http://truck.pl/ogloszenia/_getFile.asp?pdf,{0},,";
            pdfUrl = string.Format(pdfUrl, _reklama);

            if (!File.Exists(pdfFile) || File.GetLastWriteTime(pdfFile) < pdfDateTime)
            {
                WebRequestHelper.DownloadFile(pdfUrl, pdfFile);
            }

            if (!File.Exists(pdfFile))
            {
                _errorMessage = "Nie znaleziono pliku PDF: " + pdfFile;
                return false;
            }
            Process.Start(pdfFile);
            return true;
        }

        public static void CleanPdfFolder()
        {
            try
            {
                string pdfDirectory = Environment.CurrentDirectory + Path.DirectorySeparatorChar + "pdf";
                DirectoryInfo di = new DirectoryInfo(pdfDirectory);
                FileInfo[] fileInfos = di.GetFiles("*.pdf", SearchOption.TopDirectoryOnly);

                foreach (FileInfo file in fileInfos)
                {
                    if (file.CreationTime < DateTime.Now.AddMonths(-1))
                        file.Delete();
                }
            }
            catch(Exception exception)
            {
                Logger.LogException(exception, User.getUser().Login, DateTime.Now);
            }
        }
    }
}