using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Mvc;
using atakanozbancom;
using atakanozbancom.Models.classes;

namespace atakanozbancom.Controllers
{
    public class AffiliateController : Controller
    {
        private readonly Context db = new Context();

        [HttpGet]
        public ActionResult Index()
        {
            var cultureFull = Thread.CurrentThread.CurrentUICulture.Name;
            var cultureShort = Thread.CurrentThread.CurrentUICulture.TwoLetterISOLanguageName;
            var isEnglish = cultureShort == "en";

            var links = db.AffiliateLinks
                          .Include(x => x.Translations)
                          .OrderBy(x => x.sort_order)
                          .ThenBy(x => x.id)
                          .ToList();

            var model = links.Select(a =>
            {
                var title = !isEnglish
                    ? a.Translations
                        .Where(t => t.culture == cultureFull || t.culture == cultureShort)
                        .Select(t => t.title)
                        .FirstOrDefault() ?? a.title
                    : a.title;

                var description = !isEnglish
                    ? a.Translations
                        .Where(t => t.culture == cultureFull || t.culture == cultureShort)
                        .Select(t => t.description)
                        .FirstOrDefault() ?? a.description
                    : a.description;

                return new AffiliateLinkVM
                {
                    id = a.id,
                    title = title,
                    description = description,
                    url = a.url,
                    image = a.image
                };
            }).ToList();

            return View(model);
        }

        [HttpPost]
        public ActionResult ChangeLanguage(string lang)
        {
            new LanguageTR().SetLanguage(lang);
            return RedirectToAction("Index");
        }
    }
}
