Files
Phonebook/Services/DatabaseService.cs
2025-05-09 22:48:36 +03:00

108 lines
3.7 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using SQLite;
using Phonebook.Models;
using System.Collections.ObjectModel;
using Contact = Phonebook.Models.Contact;
using System.Diagnostics;
using System.Globalization;
namespace Phonebook.Services
{
public class DatabaseService
{
private SQLiteAsyncConnection _database;
public DatabaseService()
{
Initialize();
}
private async void Initialize()
{
if (_database != null)
return;
_database = new SQLiteAsyncConnection(Path.Combine(FileSystem.AppDataDirectory, "contacts.db3"),
SQLiteOpenFlags.Create | SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.SharedCache);
await _database.CreateTableAsync<Contact>();
await AddMissingColumns();
}
public async Task<List<Contact>> GetContactsAsync()
{
return await _database.Table<Contact>().ToListAsync();
}
private async Task AddMissingColumns()
{
try
{
var tableInfo = await _database.GetTableInfoAsync("Contact");
var columns = tableInfo.Select(c => c.Name).ToList();
if (!columns.Contains("Email"))
{
await _database.ExecuteAsync("ALTER TABLE Contact ADD COLUMN Email TEXT");
}
if (!columns.Contains("Address"))
{
await _database.ExecuteAsync("ALTER TABLE Contact ADD COLUMN Address TEXT");
}
}
catch (Exception ex)
{
Debug.WriteLine($"Ошибка при добавлении колонок: {ex.Message}");
}
}
public async Task<List<Contact>> SearchContactsAsync(string searchTerm)
{
if (string.IsNullOrWhiteSpace(searchTerm))
return await GetContactsAsync();
// Всегда получаем все контакты и фильтруем в памяти
// Это обеспечит одинаковое поведение для всех языков
var allContacts = await GetContactsAsync();
var compareInfo = CultureInfo.CurrentCulture.CompareInfo;
return allContacts?
.Where(c =>
compareInfo.IndexOf(c.Name ?? "", searchTerm, CompareOptions.IgnoreCase) >= 0 ||
compareInfo.IndexOf(c.PhoneNumber ?? "", searchTerm, CompareOptions.IgnoreCase) >= 0 ||
compareInfo.IndexOf(c.Email ?? "", searchTerm, CompareOptions.IgnoreCase) >= 0 ||
compareInfo.IndexOf(c.Address ?? "", searchTerm, CompareOptions.IgnoreCase) >= 0 ||
compareInfo.IndexOf(c.Description ?? "", searchTerm, CompareOptions.IgnoreCase) >= 0)
.DistinctBy(c => c.Id)
.ToList() ?? new List<Contact>();
}
private bool ContainsCyrillic(string text)
{
return text.Any(c => c >= 'а' && c <= 'я' || c >= 'А' && c <= 'Я');
}
public async Task<Contact> GetContactAsync(int id)
{
return await _database.Table<Contact>().Where(c => c.Id == id).FirstOrDefaultAsync();
}
public async Task<int> SaveContactAsync(Contact contact)
{
if (contact.Id != 0)
{
return await _database.UpdateAsync(contact);
}
else
{
return await _database.InsertAsync(contact);
}
}
public async Task<int> DeleteContactAsync(Contact contact)
{
return await _database.DeleteAsync(contact);
}
}
}