﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using DiaryOfMadman.Models;
using DiaryOfMadman.Repositories;

namespace DiaryOfMadman.Services
{
    public class NoteService
    {
        private readonly INoteRepository _noteRepository;
        private readonly UserService _userService;

        private const int Take = 30;

        public NoteService(INoteRepository noteRepository, UserService userService)
        {
            _noteRepository = noteRepository;
            _userService = userService;
        }

        public async Task<IEnumerable<MadmanNote>> GetNotesAsync(int page)
        {
            var user = await _userService.GetCurrentUserAsync();

            if (user == null)
            {
                return null;
            }

            var result = await _noteRepository.GetNotesAsync(user.UserId, Take, Take * (page - 1));

            return result;
        }

        public async Task CreateNoteAsync(MadmanNote note)
        {
            if (note == null)
            {
                throw new ArgumentNullException(nameof(note));
            }

            var user = await _userService.GetCurrentUserAsync();

            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }

            if (string.IsNullOrWhiteSpace(note.Header) || string.IsNullOrWhiteSpace(note.Body))
            {
                throw new Exception("Заголовок и содержание обязательны для заполнения");
            }

            note.AuthorId = user.UserId;
            note.Created = DateTime.UtcNow;

            await _noteRepository.InsertNoteAsync(note);
        }
    }
}