package com.style24.front.support.util;

import javax.servlet.http.HttpServletRequest;

import org.springframework.mobile.device.Device;
import org.springframework.mobile.device.DeviceUtils;
import org.springframework.mobile.device.site.SitePreference;
import org.springframework.mobile.device.site.SitePreferenceUtils;
import org.springframework.mobile.device.util.ResolverUtils;
import org.springframework.util.Assert;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.style24.front.support.env.TsfConstants;

import lombok.extern.slf4j.Slf4j;

import com.gagaframework.web.util.GagaCookieUtil;

/**
 * 디바이스 뷰 관련 Util Class
 * 
 * @author gagamel
 * @since 2021. 3. 30
 */
@Slf4j
public class ViewUtils {

	public static String getDeviceViewName(String viewName) {
		RequestAttributes attrs = RequestContextHolder.getRequestAttributes();
		Assert.isInstanceOf(ServletRequestAttributes.class, attrs);
		HttpServletRequest request = ((ServletRequestAttributes)attrs).getRequest();

		Device device = DeviceUtils.getCurrentDevice(request);
		SitePreference sitePreference = SitePreferenceUtils.getCurrentSitePreference(request);
		String resolvedViewName = viewName;

		if (ResolverUtils.isNormal(device, sitePreference)) {
			resolvedViewName = "web/" + viewName + "Web";
		} else if (ResolverUtils.isMobile(device, sitePreference)) {
			if (GagaCookieUtil.getCookie(request, TsfConstants.CK_PREFIX + "_site_preference").equals("normal")) {
				resolvedViewName = "web/" + viewName + "Web";
			} else {
				resolvedViewName = "mob/" + viewName + "Mob";
			}
		} else if (ResolverUtils.isTablet(device, sitePreference)) {
			if (GagaCookieUtil.getCookie(request, TsfConstants.CK_PREFIX + "_site_preference").equals("normal")) {
				resolvedViewName = "web/" + viewName + "Web";
			} else {
				resolvedViewName = "mob/" + viewName + "Mob";
			}
		}

		log.info("resolvedViewName: {}", resolvedViewName);

		return stripTrailingSlash(resolvedViewName);
	}

	private static String stripTrailingSlash(String viewName) {
		if (viewName.endsWith("//")) {
			return viewName.substring(0, viewName.length() - 1);
		}

		return viewName;
	}

}
