// 
// Copyright (c) 2013-2016 Carsten Sonne Larsen <cs@innolan.dk>
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// 
// 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.IO;
using Ntp.Analyzer.Log;
using Ntp.Common.IO;
using Ntp.Common.Log;

namespace Ntp.Analyzer.Export
{
    public abstract class FileSystemDestination : StreamDestination
    {
        public static uint? FileUserId = null;
        public static uint? FileGroupId = null;
        public static uint FileMask = 644;

        protected static void ApplyPermissions(string file, LogBase log)
        {
            if (FileUserId != null)
            {
                try
                {
                    if (!Permission.ChangeFileOwner(file, FileUserId.Value, FileGroupId))
                    {
                        log.DestinationOwnerError(file);
                    }
                }
                catch (Exception e)
                {
                    log.DestinationOwnerError(file, e);
                }
            }

            try
            {
                if (!Permission.ChangeFileMode(file, FileMask))
                {
                    log.DestinationPermissonError(file);
                }
            }
            catch (Exception e)
            {
                log.DestinationPermissonError(file, e);
            }
        }

        protected static string JoinPath(string path1, string path2)
        {
            string a = path1 ?? string.Empty;
            string b = path2 ?? string.Empty;

            a = a.TrimEnd(Path.DirectorySeparatorChar).TrimEnd(Path.AltDirectorySeparatorChar);
            b = b.TrimStart(Path.DirectorySeparatorChar).TrimStart(Path.AltDirectorySeparatorChar);

            string c = string.Concat(a, Path.DirectorySeparatorChar, b);
            return ScrubPath(c);
        }

        protected static string JoinPath(string path1, string path2, string path3)
        {
            return JoinPath(JoinPath(path1, path2), path3);
        }

        protected static void PrepareFile(string file, LogBase log)
        {
            string created = null;
            try
            {
                created = DirectoryCommand.CreateRecursiveFromFile(file);
            }
            catch (Exception e)
            {
                log.DestinationPathError(file, e);
            }

            if (created != null)
            {
                log.DestinationNewDirectory(created);
            }

            if (File.Exists(file))
                File.Delete(file);
        }

        protected static void TestFile(string file, string content)
        {
            if (File.Exists(file))
                File.Delete(file);

            File.WriteAllText(file, content);
            File.Delete(file);
        }

        protected static void WriteFile(Stream stream, string file, LogBase log)
        {
            try
            {
                using (var fileStream = new FileStream(file, FileMode.CreateNew))
                    stream.CopyTo(fileStream);

                log.WroteFile(file);
            }
            catch (Exception e)
            {
                log.DestinationFileError(file, e);
            }
        }

        private static string ScrubPath(string path)
        {
            return path.Trim().
                Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
        }
    }
}