using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using System.IO;
//using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using Microsoft.EntityFrameworkCore;

namespace RestAPI2.Pages
{
    public class ApartmentModel : PageModel
    {
        private readonly RestAPI2.Data.HouseContext _context;

        public ApartmentModel(RestAPI2.Data.HouseContext context)
        {
            _context = context;
        }
        public IList<RestAPI2.Models.Apartment> Apartments { get;set; }

        public async Task OnGetAsync()
        {
            Apartments = await _context.Apartments.ToListAsync();
        }
        private IWebHostEnvironment _environment;
        // public HouseModel(IWebHostEnvironment environment)
        // {
        //     _environment = environment;
        // }
     
        [BindProperty]
        public IFormFile Upload { get; set; }
        public async Task<IActionResult> OnPostAsync()
        {

            Console.WriteLine(Upload.Length);
            using (var reader = new StreamReader(Upload.OpenReadStream()))
            {
                
                while (reader.Peek() >= 0){
                    RestAPI2.Models.Apartment h=new RestAPI2.Models.Apartment();
                    string line=reader.ReadLine();
                    var list=line.Split(",");
                    if(list.Length>4){
                        h.Number=Int32.Parse(list[0]);
                        h.ID=h.Number;
                        h.Floor=Int32.Parse(list[1]);
                        h.NumberRoom=Int32.Parse(list[2]);
                        h.Population=Int32.Parse(list[3]);
                        h.FullArea=float.Parse(list[4]);
                        h.LivingSpace=(list[4]);
                        h.HouseNumber=Int32.Parse(list[5]);
                        
                        try{
                            _context.Apartments.Add(h);
                             await _context.SaveChangesAsync();
                        }catch{

                        }
                    }
                     
                     
                }
                   
            }
            // Console.WriteLine(_environment.ContentRootPath);
            // var file = Path.Combine(_environment.ContentRootPath, "uploads", Upload.FileName);
            // using (var fileStream = new FileStream(file, FileMode.Create))
            // {
            //     await Upload.CopyToAsync(fileStream);
            // }
            return RedirectToPage("./Apartment");
        }
        
    }
}
