using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using SQLite;
using TodoList.Models;

namespace TodoList.Services
{
    public class SqliteDataService : IDataService
    {
        private readonly SQLiteAsyncConnection _database;

        public SqliteDataService()
        {
            var appData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
            var folder = Path.Combine(appData, "TodoListApp");
            Directory.CreateDirectory(folder);
            var databasePath = Path.Combine(folder, "TodoList.sqlite");

            _database = new SQLiteAsyncConnection(databasePath);
            _database.CreateTableAsync<TodoItem>().Wait();
        }

        public async Task<List<TodoItem>> LoadTasksAsync(bool? completed = null)
        {
            var query = _database.Table<TodoItem>();
            if (completed.HasValue)
            {
                query = query.Where(t => t.IsCompleted == completed.Value);
            }
            return await query.ToListAsync();
        }

        public async Task<TodoItem> SaveTaskAsync(TodoItem task)
        {
            await _database.InsertOrReplaceAsync(task);
            return task;
        }

        public async Task<TodoItem> UpdateTaskAsync(TodoItem task)
        {
            await _database.UpdateAsync(task);
            return task;
        }

        public async Task<TodoItem> ToggleCompleteAsync(string id)
        {
            var task = await _database.FindAsync<TodoItem>(id);
            if (task != null)
            {
                task.IsCompleted = !task.IsCompleted;
                task.CompletedAt = task.IsCompleted ? DateTime.Now : null;
                task.SyncStatus = SyncStatus.Pending;
                await _database.UpdateAsync(task);
            }
            return task;
        }

        public async Task SaveAllAsync(List<TodoItem> tasks)
        {
            await _database.RunInTransactionAsync(tran =>
            {
                foreach (var task in tasks)
                {
                    tran.InsertOrReplace(task);
                }
            });
        }

        public async Task DeleteTaskAsync(string id)
        {
            await _database.DeleteAsync<TodoItem>(id);
        }
    }
}
