using Valg.EVA.Skanning.ServicesModel.ServiceContracts.Box.Read;
using Valg.EVA.Skanning.Services.Scan;
using Valg.EVA.Skanning.UserInterfaceElements;

namespace Valg.Eva.Skanning.Scan.Presentation.MainWindow
{
    public class BoxScanningSession : ViewModelBase
    {
        private BoxCountingWithElectionData box;
        private readonly int countingId;
        private readonly IScanService scanService;
        private byte[] lastScannedImage;
        private int numberOfBallotsScanned;
        private int lastImageFrontRotation;
        public int LastImageFrontRotation
        {
            get => lastImageFrontRotation;
            private set
            {
                lastImageFrontRotation = value; 
                OnPropertyChanged();
            }
        }
        public static readonly BoxScanningSession EmptySession = new BoxScanningSession(new BoxCountingWithElectionData(new BoxCounting()));

        private BoxScanningSession(BoxCountingWithElectionData box)
        {
            this.box = box;
        }

        public BoxScanningSession(int countingId, IScanService scanService, string countingEmlAreaContextId)
        {
            this.countingId = countingId;
            this.scanService = scanService;
            CountingEmlAreaContextId = countingEmlAreaContextId;
        }

        public bool HasScannedBallots => NumberOfBallotsScanned > 0;

        public string CountingEmlAreaContextId { get; }

        public BoxCountingWithElectionData Box => box;

        public int CountingId => countingId;

        public void ResetSessionData()
        {
            LastScannedImage = new byte[] { };
            LastImageFrontRotation = 0;
            NumberOfBallotsScanned = 0;
            LastDatabaseCallFailed = false;
        }

        public void ReloadBoxModel(string barcodeLong, string barcodeShort)
        {
            box = scanService.GetBoxCountingWithElectionData(barcodeLong, barcodeShort, countingId);
            LastDatabaseCallFailed = false;
        }

        public byte[] LastScannedImage
        {
            get { return lastScannedImage; }
            private set
            {
                lastScannedImage = value;
                OnPropertyChanged();
            }
        }

        public int NumberOfBallotsScanned
        {
            get { return numberOfBallotsScanned; }
            private set
            {
                numberOfBallotsScanned = value;
                OnPropertyChanged();
            }
        }

        public void AnotherBallotWasScanned(byte[] lastImage, int rotation)
        {
            LastImageFrontRotation = rotation;
            LastScannedImage = lastImage;
            NumberOfBallotsScanned = NumberOfBallotsScanned + 1;
        }

        public bool LastDatabaseCallFailed { get; set; }
    }
}
