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 ResidentModel : PageModel
    {
        private readonly RestAPI2.Data.HouseContext _context;

        public ResidentModel(RestAPI2.Data.HouseContext context)
        {
            _context = context;
        }
        public IList<RestAPI2.Models.Resident> Residents { get;set; }

        public async Task OnGetAsync()
        {
            Residents = await _context.Residents.ToListAsync();
        }
        private IWebHostEnvironment _environment;
        // public ResidentModel(IWebHostEnvironment environment)
        // {
        //     _environment = environment;
        // }
        public int ResidentId { get; set; }
        public string Street { get; set; }
        public string TownName { get; set; }
        public int Index { get; set; }


        [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.Resident h=new RestAPI2.Models.Resident();
                    string line=reader.ReadLine();
                    var list=line.Split(",");
                    if(list.Length>3){
                        h.First=(list[0]);
                        h.Surname=list[1];
                        h.PersonalCode=list[2];
                        h.Dateofbirth=list[3];
                        h.Phone=list[4];
                        h.Email=list[5];
                        h.ApartmentNumber=Int32.Parse(list[5]);
                        try{
                            _context.Residents.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("./Resident");
        }
        
    }
}
