using System;
using Valg.EVA.Skanning.Contracts.CommonEnums;
using Valg.EVA.Skanning.JobManagement.Startup.Data;
using Valg.EVA.Skanning.JobManagement.Startup.Data.Transfer;
using Valg.EVA.Skanning.Resources.Language;

namespace Valg.EVA.Skanning.JobManagement.Startup.UI.TransferOverview
{
    public class TransferViewModel : ReactiveViewModel
    {
        private CountingCompleteModel model;
        
        public void Initialize(CountingCompleteModel countingCompleteModel)
        {
            model = countingCompleteModel;

            model.Bubble(
                m => m.State,
                this,
                vm => vm.State,
                vm => vm.Status,
                vm => vm.IsErrorState,
                vm => vm.IsSuccessState);

            model.Bubble(
                m => m.ErrorCode,
                this,
                vm => vm.ErrorCode);

            model.Bubble(
                from => from.CheckStatusForTransferManually,
                this,
                to => to.CheckStatusForTransferManually);
        }

        public int TransferJobId => model.Transfer.Id;
        public int CountingId => model.Counting.Id;

        public string CountingName => model.Counting.Name;

        public string Status
        {
            get
            {
                var timestampToUse = model.Transfer.Created;

                if (model.Transfer.Updated.HasValue)
                    timestampToUse = model.Transfer.Updated.GetValueOrDefault();

                var resourceKey = $"TransferState_{model.State.Name}";
                var resource = JobManagementLanguageString.ResourceManager.GetString(resourceKey, JobManagementLanguageString.Culture);
                return string.Format(resource, timestampToUse.ToString("G"));
            }
        }

        public TransferState State => model.State;

        public bool IsErrorState => State.Equals(TransferState.ErrorOnServer) || State.Equals(TransferState.FileTransferFailed);

        public string ErrorCode => model.ErrorCode;

        public CountingType CountingType => model.Counting.CountingType;

        public bool CheckStatusForTransferManually => model.CheckStatusForTransferManually;

        public bool IsSuccessState => State.Equals(TransferState.FinishedOnServer);
        public int TransferId => model.Transfer.LatestTransferId.GetValueOrDefault();
        public DateTime Updated => model.Transfer.Updated.GetValueOrDefault();
    }
}
