using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Kavenegar;
using Kavenegar.Core.Exceptions;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Moshaverino.Core.Models;

namespace Moshaverino.Core.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class StudentController : Controller
    {
        private readonly MoshaverinoContext _context;
        public StudentController(MoshaverinoContext context)
        {
            _context = context;
        }
        [HttpPost("Code")]
        public async Task<IActionResult> GetCode(string phoneNumber)
        {
            try
            {
                if (IsStudentExist(phoneNumber))
                {
                    var student = _context.Students.FirstOrDefault(u => u.PhoneNumber == phoneNumber);
                    SendSms(student.PhoneNumber, student.Code);
                    return Ok(student);
                }

                else
                {
                    var st = new Student
                    {
                        PhoneNumber = phoneNumber,
                        Code = GetRandomCode()
                    };
                    _context.Students.Add(st);
                    _context.SaveChanges();
                    SendSms(st.PhoneNumber, st.Code);
                    return Ok(st);
                }
            }
            catch (Exception e)
            {
                return BadRequest(e.Message);
            }
        }
        [HttpGet("Code")]
        public async Task<IActionResult> CheckCode(string code)
        {
            try
            {
                return Ok(_context.Students.Any(s=>s.Code==code));
            }
            catch (Exception e)
            {
                return BadRequest(e.Message);
            }
        }

        [HttpPost("SetInfo")]
        public async Task<IActionResult> SetStudentInfo(Student student)
        {
            try
            {
                _context.Entry<Student>(student).State = EntityState.Modified;
                _context.SaveChanges();
                return Ok(student);
            }
            catch (Exception e)
            {
                return BadRequest(e.Message);
            }
        }

        private bool IsStudentExist(string phoneNumber)
        {
            return _context.Students.Any(s => s.PhoneNumber == phoneNumber);
        }

        private async Task<bool> SendSms(string phoneNumber, string code)
        {
            try
            {
                var api = new KavenegarApi(
                    "32433666522B516838714779627679525877746E457337536A377663526A543265646650372F456F774F413D");
                var result = await api.VerifyLookup(phoneNumber, code, "verifyPhone");
                if (result.Status == 200)
                    return true;
                else
                    return false;
            }
            catch (ApiException e)
            {
                return false;
            }
        }

        private string GetRandomCode()
        {
            Random random = new Random(DateTime.Now.Millisecond);
            var code = random.Next(111111, 999999);
            if (_context.Students.Any(s => s.Code == code.ToString()))
                return GetRandomCode();
            else
                return code.ToString();
        }
    }
}