
// Created with MonoDevelop
//
//    QuickStep: Acquire, view and identify spectra 
//    Copyright (C) 2021 Hiperscan GmbH Dresden, Germany
//
//    This program is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    This program is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with this program.  If not, see <http://www.gnu.org/licenses/>.


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

namespace Hiperscan.Extensions.ApoIdentSoftwareUpgrade
{
    public partial class Upgrader
    {
        private void DownLoad()
        {
            this.DownloadFile(this.QuickStepLookupUnit);
            this.DownloadFile(this.IdentModuleLookupUnit);
            this.DownloadFile(this.QuantifierModuleLookopUnit);
        }

        private void DownloadFile(LookupUnit lookup_unit)
        {
            if (this.DeleteOldFiles(lookup_unit))
            {
                if (this.StartDownLoadProcess(lookup_unit))
                    this.MoveDownloadFile(lookup_unit);
            }
        }

        private bool DeleteOldFiles(LookupUnit lookup_unit)
        {
            try
            {
                if (lookup_unit.CanDownload == false)
                    return true;

                Console.WriteLine("Delete old download files ({0}) ...", lookup_unit.ProjectType);

                foreach (FileInfo file in this.GetDownloadFiles(lookup_unit))
                {
                    if (lookup_unit.IsDownloadFile(file) == true)
                        continue;

                    Console.WriteLine("Delete,{0}", file);
                    file.Delete();
                }

                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine("Cannot delete old downoad files: {0}", ex);
                return false;
            }
        }

        private bool StartDownLoadProcess(LookupUnit lookup_unit)
        {
            try
            {
                if (lookup_unit.CanDownload == false)
                    return true;

                if (this.FileExists(lookup_unit))
                {
                    Console.WriteLine("File is already downloaded.");
                    return true;
                }

                Console.WriteLine("Start downloading ({0}) ...", lookup_unit.ProjectType);

                string dir = this.GetFullDownloadDirectoryName(lookup_unit.ProjectLocale);
                if (Directory.Exists(dir) == false)
                    Directory.CreateDirectory(dir);

                Process proc = new Process();
                proc.StartInfo.FileName = "curl";
                proc.StartInfo.Arguments = string.Format(" -L {0} --output {1}",
                                                         lookup_unit.Url,
                                                         lookup_unit.TmpFileName);

                proc.StartInfo.CreateNoWindow = true;
                proc.StartInfo.UseShellExecute = false;
                proc.StartInfo.RedirectStandardOutput = true;
                proc.StartInfo.WorkingDirectory = dir;

                Console.WriteLine(proc.StartInfo.Arguments);

                proc.Start();
                proc.WaitForExit();

                if (proc.ExitCode != 0)
                    throw new Exception(String.Format("Exited with {0}", proc.ExitCode));

                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine("Download failed: {0}", ex);
                return false;
            }
        }

        private void MoveDownloadFile(LookupUnit lookup_unit)
        {
            try
            {
                if (lookup_unit.CanDownload == false)
                    return;

                if (this.FileExists(lookup_unit))
                    return;

                Console.WriteLine("Moving file ({0}) ...", lookup_unit.ProjectType);

                string dir = this.GetFullDownloadDirectoryName(lookup_unit.ProjectLocale);
                FileInfo tmp_file = new FileInfo(Path.Combine(dir, lookup_unit.TmpFileName));
                if (tmp_file.Length != lookup_unit.FileLength)
                    throw new Exception("Temp file does not have the correct length.");

                FileInfo destination = new FileInfo(Path.Combine(dir, lookup_unit.FileName));
                File.Move(tmp_file.FullName, destination.FullName);
                destination.CreationTime = lookup_unit.PublisherDate;

                destination = new FileInfo(destination.FullName);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Moving file failed: {0}", ex);
            }
        }

        private bool FileExists(LookupUnit lookup_unit)
        {
            try
            {
                string dir = this.GetFullDownloadDirectoryName(lookup_unit.ProjectLocale);
                FileInfo file = new FileInfo(Path.Combine(dir, lookup_unit.FileName));

                return lookup_unit.IsDownloadFile(file);                               
            }
            catch (Exception)
            {
                return false;
            }
        }
    }
}
