﻿using FieldApp.Models;
using SQLite;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FieldApp.Data
{
    public class FieldAppDatabase
    {
        readonly SQLiteAsyncConnection database;

        public FieldAppDatabase(string dbPath)
        {
            database = new SQLiteAsyncConnection(dbPath);
            database.CreateTableAsync<EquipmentLocal>().Wait();
        }

        public Task<List<EquipmentLocal>> GetItemsAsync()
        {
            return database.Table<EquipmentLocal>().ToListAsync();
        }

        public Task<List<EquipmentLocal>> GetItemsNotDeletedAsync()
        {
            return database.QueryAsync<EquipmentLocal>("SELECT * FROM [EquipmentLocal] WHERE [IsDeleted] = 0");
        }

        public Task<EquipmentLocal> GetItemAsync(int id)
        {
            return database.Table<EquipmentLocal>().Where(i => i.Id == id).FirstOrDefaultAsync();
        }

        public Task<int> SaveItemAsync(EquipmentLocal item)
        {
            if (item.Id != 0)
            {
                return database.UpdateAsync(item);
            }
            else
            {
                return database.InsertAsync(item);
            }
        }

        public Task<int> DeleteItemAsync(EquipmentLocal item)
        {
            return database.DeleteAsync(item);
        }
    }
}
