﻿using System.IO;
using System.Linq;
using beacon.service.Persisters;
using Xunit;

namespace beacon.service.tests
{
    public class ScriptPersisterTests
    {
        public ScriptPersisterTests()
        {
            if (Directory.Exists("scripts"))
                Directory.Delete("scripts", true);
        }

        [Fact]
        public void Delete_ShouldDelete()
        {
            using (var persister = new ScriptPersister("scripts"))
            {
                var sourceRecord = new ScriptRecord
                {
                    Key = "key3",
                    Body = "body"
                };
                persister.Save(sourceRecord);
                persister.Delete("key3");
                var targetRecords = persister.GetAll().Where(x => x.Key == "key3");
                Assert.Equal(0, targetRecords.Count());
            }
        }

        [Fact]
        public void GetAll_ShouldGetAll()
        {
            using (var persister = new ScriptPersister("scripts"))
            {
                var sourceRecord1 = new ScriptRecord
                {
                    Key = "key1",
                    Body = "body1"
                };
                var sourceRecord2 = new ScriptRecord
                {
                    Key = "key2",
                    Body = "body2"
                };
                persister.Save(sourceRecord1);
                persister.Save(sourceRecord2);
                var all = persister.GetAll();

                Assert.Equal(2, all.Count);
            }
        }

        [Fact]
        public void Save_ShouldPersist()
        {
            using (var persister = new ScriptPersister("scripts"))
            {
                var sourceRecord = new ScriptRecord
                {
                    Key = "key",
                    Body = "body"
                };
                persister.Save(sourceRecord);
                var targetRecord = persister.GetAll().First(x => x.Key == "key");
                Assert.Equal(sourceRecord.Key, targetRecord.Key);
                Assert.Equal(sourceRecord.Body, targetRecord.Body);
            }
        }
    }
}