using System;
using System.Collections.Generic;
using System.Data.SQLite;
using System.IO;
using KellermanSoftware.ContactsModule.Models;
using KellermanSoftware.NetDataAccessLayer;

namespace KellermanSoftware.ContactsModule.DataAccess
{
    public class Repository : IRepository
    {
        
        private readonly IDataHelper _db;

        private string DatabasePath
        {
            get { return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "DalDemoDatabase.db"); }
        }

        public string BuildConnectionString()
        {
            SQLiteConnectionStringBuilder builder = new SQLiteConnectionStringBuilder();
            builder.DataSource = DatabasePath;
            return builder.ConnectionString;

        }
        public Repository()
        {
            string connectionString = BuildConnectionString();

            //Get a thread static safe session
            _db =  DataHelper.SessionFactory();
            _db.ConnectionString = connectionString;

            CreateDatabaseIfItDoesntExist();
        }

        public void CreateDatabaseIfItDoesntExist()
        {
            _db.Setup("KellermanSoftware.ContactsModule.Models");
        }
        
        public void DeleteHistory(ContactHistory history)
        {
            _db.Delete(history);
        }

        public void DeleteContact(long primaryKey)
        {
            _db.DeleteWithChildren<Contact>(primaryKey);
        }

        public void SaveContact(Contact contact)
        {
            _db.SaveWithChildren(contact);
        }

        public Contact LoadContact(long primaryKey)
        {
            return _db.LoadWithChildren<Contact>(primaryKey);
        }

        public List<ContactName> LoadContactNames()
        {
            const string SQL = "SELECT ContactId, Name FROM Contacts ORDER BY Name";
            return _db.Load<ContactName>(SQL);
        }
    }
}
