using Dashboard.Contexto.Data;
using Dashboard.Contexto.Models;
using Dashboard.Dominio.Components;
using Dashboard.Dominio.Interfaces;
using Dashboard.Dominio.ViewModel;
using Infraestrutura.ElmahLog;
using System;
using System.Data.Entity;
using System.Web.Configuration;
using System.Web.Mvc;

namespace Dashboard.Dominio.Servicos.Relatorios
{
    public class ViagemColetaOcupacaoController : Controller
    {
        public ActionResult Index(string id = "", int? width = null, int? height = null, string firebird = "", string mysql = "", string filtros = "",
            string titulo = "", string fontColor = "", string backgroundColor = "", string Position = "", string requisicaointerna = "")
        {
            try
            {
                Util.SetRequisicaoInterna = requisicaointerna.Trim().ToLower().Equals("1");
                if (string.IsNullOrEmpty(id))
                {
                    var filtro = new Filtro(filtros);
                    if (!filtro.ContemValores())
                        return new JsonResult() { JsonRequestBehavior = JsonRequestBehavior.AllowGet };

                    var config = new ContextConfigService();
                    var context = !string.IsNullOrEmpty(mysql.Replace(",", "")) ? config.ConfigMySql(mysql) : GetDatabase(config, firebird);
                    var service = new ViagemColetaOcupacaoService(new Repository<ViagemColetaOcupacao>(context), new Repository<Setores>(context), filtro);

                    var viewModel = (IBaseViewModel)service.GetData();
                    viewModel.id = id;
                    viewModel.width = width;
                    viewModel.height = height;
                    viewModel.firebird = firebird;
                    viewModel.mysql = mysql;
                    viewModel.filtros = filtros;
                    viewModel.ServerAddress = WebConfigurationManager.AppSettings[Util.GetRequisicaoInterna];
                    viewModel.DashboardTitle = titulo;
                    viewModel.FontColor = fontColor;
                    viewModel.BackgroundColor = backgroundColor;
                    viewModel.Title = "Relatório de Taxa de Ocupação";
                    return View("Index", viewModel);
                }
                else
                {
                    var filtro = new Filtro(filtros);
                    var filter = new ViagemColetaOcupacaoService(filtro).GetFilter();
                    return filter;
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
                return View("../Error/_404");
            }
        }

        private DbContext GetDatabase(ContextConfigService config, string firebird) =>
           !string.IsNullOrEmpty(firebird.Replace(",", "")) ? config.ConfigFirebird(firebird) : new ContextEntity("ConnectionEntity");
    }
}
