﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Alphaleonis.Win32.Filesystem;
using NLog;

using HIO.Backup.Model;
using HIO.Backup.Interface;
using HIO.Backup.Interface.Persistence;
using HIO.Backup.Persistence.Disk;
using HIO.Backup.Destination;

namespace HIO.Backup.Persistence
{
    public class StorageProvider
    {
        private ILogger log = LogManager.GetCurrentClassLogger();

        // - new
        public IDestination Destination { get; private set; } = null;

        public IBackupObjStorage BackupObjStorage { get; private set; } = null;
        public IBackupDestinationStorage BackupDestinationStorage { get; private set; } = null;
        //public IJobStorage JobStorage { get; private set; } = null;
        //public IJobQueueStorage JobQueueStorage { get; private set; } = null;


        public StorageProvider(IDestination destination)
        {
            this.Destination = destination;

            if (this.Destination.IsConnected)
            {
                this.Init();
            }
            else
            {
                // Init when the provider connects
                this.Destination.OnFirstConnection += (sender, e) => { this.Init(); };
            }
        }


        private void Init()
        {
            // Factory
            /*
            if (this.Destination is ExternalDestination2)
            {
                ExternalDestination2 tmp = (ExternalDestination2)this.Destination;
                this.BackupDestinationStorage = new BackupDestinationDiskStorage(tmp.ConfigDatabase, this.log);
                this.BackupObjStorage = new BackupObjDiskStorage(tmp.ConfigDatabase, this.log);
                //this.JobStorage = new JobDiskStorage(tmp.ConfigDatabase, this.log);
            }
            else
            {
                throw new NotImplementedException("No other types supported atm");
            }
            */
        }


        public async Task SyncAsync(StorageProvider appData, CancellationToken cToken)
        {
            if (cToken.IsCancellationRequested) return;

            if (!this.Destination.IsConnected)
            {
                this.log.Warn("Destination '{0}' not connected, will not sync to it", this.Destination.Id);
                return;
            }

            await Sync.SyncMultipleItems(appData.BackupObjStorage, this.BackupObjStorage, cToken);
            //await Sync.SyncMultipleItems(appData.JobStorage, this.JobStorage, cToken);
            //await Sync.SyncOneItem(appData.JobQueueStorage, this.JobQueueStorage, cToken);
            await Sync.SyncMultipleItems(appData.BackupDestinationStorage, this.BackupDestinationStorage, cToken);
        }
    }
}
