using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using StockFin.Models;

namespace StockFin.Controllers
{
    public class TransactionsController : Controller
    {
        private readonly FinancesContext _context = new FinancesContext();

        //public TransactionsController(FinancesContext context)
        //{
        //    _context = context;
        //}

        // GET: Transactions
        public async Task<IActionResult> Index()
        {
            var transactions = await _context.Transactions
                .Include(t => t.Account)
                .Include(t => t.Stocks)
                .OrderByDescending(t => t.Date)
                .ToListAsync();

            return View(transactions);
        }

        // GET: Transactions/Create
        public async Task<IActionResult> Create()
        {
            await PopulateAccountsAndStocksDropDownsAsync();
            return View();
        }

        // POST: Transactions/Create
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("Id,TypeId,AccountId,StocksId,Quantity,Value,Date")] Transaction transaction)
        {
            if (ModelState.IsValid)
            {
                _context.Add(transaction);
                await _context.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }

            await PopulateAccountsAndStocksDropDownsAsync(transaction.AccountId, transaction.StocksId);
            return View(transaction);
        }

        // GET: Transactions/Edit/5
        public async Task<IActionResult> Edit(long? id)
        {
            if (id == null)
                return NotFound();

            var transaction = await _context.Transactions.FindAsync(id.Value);
            if (transaction == null)
                return NotFound();

            await PopulateAccountsAndStocksDropDownsAsync(transaction.AccountId, transaction.StocksId);
            return View(transaction);
        }

        // POST: Transactions/Edit/5
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(long id, [Bind("Id,TypeId,AccountId,StocksId,Quantity,Value,Date")] Transaction transaction)
        {
            if (id != transaction.Id)
                return NotFound();

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(transaction);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!TransactionExists(transaction.Id))
                        return NotFound();
                    else
                        throw;
                }

                return RedirectToAction(nameof(Index));
            }

            await PopulateAccountsAndStocksDropDownsAsync(transaction.AccountId, transaction.StocksId);
            return View(transaction);
        }

        // GET: Transactions/Delete/5
        public async Task<IActionResult> Delete(long? id)
        {
            if (id == null)
                return NotFound();

            var transaction = await _context.Transactions
                .Include(t => t.Account)
                .Include(t => t.Stocks)
                .FirstOrDefaultAsync(m => m.Id == id.Value);

            if (transaction == null)
                return NotFound();

            return View(transaction);
        }

        // POST: Transactions/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> DeleteConfirmed(long id)
        {
            var transaction = await _context.Transactions.FindAsync(id);
            if (transaction != null)
            {
                _context.Transactions.Remove(transaction);
                await _context.SaveChangesAsync();
            }

            return RedirectToAction(nameof(Index));
        }

        private bool TransactionExists(long id)
        {
            return _context.Transactions.Any(e => e.Id == id);
        }

        private async Task PopulateAccountsAndStocksDropDownsAsync(long? selectedAccountId = null, long? selectedStockId = null)
        {
            var accounts = await _context.Accounts.OrderBy(a => a.Title).Select(a => new
            {
                a.Id,
                DisplayTitle = a.Bank+ " - " + a.Title
            }).ToListAsync();
            var stocks = await _context.Stocks.OrderBy(s => s.Title).ToListAsync();

            ViewData["AccountId"] = new SelectList(accounts, "Id", "DisplayTitle", selectedAccountId);
            ViewData["StocksId"] = new SelectList(stocks, "Id", "Title", selectedStockId);
        }
    }
}
