# -*- coding: UTF-8 -*-
import attr
import random
import asyncio
import aiohttp

from .. import _util, _exception

class State(object):
	def __init__(cls):
		cls._config = {}
		cls._headers = _util.HEADERS
		cls._cookies = _util.COOKIES
		cls.user_id = None
		cls.user_imei = None
		cls._loggedin = False
	
	def is_logged_in(cls):
		return cls._loggedin
	
	def set_cookies(cls, cookies):
		cls._cookies = cookies
	
	def set_secret_key(cls, secret_key):
		cls._config["secret_key"] = secret_key
	
	async def get_cookies(cls):
		return cls._cookies
	
	async def get_secret_key(cls):
		return cls._config.get("secret_key")
	
	async def _get(cls, *args, **kwargs):
		async with aiohttp.ClientSession() as session:
			async with session.get(*args, **kwargs, headers=cls._headers, cookies=cls._cookies) as response:
				return await response.json(content_type=None)
		
	async def _post(cls, *args, **kwargs):
		async with aiohttp.ClientSession() as session:
			async with session.post(*args, **kwargs, headers=cls._headers, cookies=cls._cookies) as response:
				return await response.json(content_type=None)
	
	async def login(cls, phone, password, imei, session_cookies=None, user_agent=None):
		if cls._cookies and cls._config.get("secret_key"):
			cls._loggedin = True
			return
			
		if user_agent:
			cls._headers["User-Agent"] = user_agent
			
		if cls._cookies:
			try:
				data = await cls._get(f"https://wpa.chat.zalo.me/api/login/getLoginInfo?imei={imei}&type=30&client_version=655&computer_name=Tahn&ts={_util.now()}")
				# data = response.json()
				data = {
					"data": {
						"phone_number": str(data["data"]["phone_number"]),
						"secret_key": str(data["data"]["zpw_enk"]),
						"send2me_id": str(data["data"]["uid"]),
						"zpw_ws": data["data"]["zpw_ws"],
						"cloud_id": data["data"]["send2me_id"],
					},
					"error_code": 0
				}
				if data.get("error_code") == 0:
					cls._config = data.get("data")
					
					if cls._config.get("secret_key"):
						cls._loggedin = True
						cls.user_id = cls._config.get("send2me_id")
						cls.user_imei = imei
						
					else:
						cls._loggedin = False
						raise _exception.ZaloLoginError("Unable to get `secret key`.")
						
				else:
					error = data.get("error_code")
					content = data.get("error_message")
					raise _exception.ZaloLoginError(f"Error #{error} when logging in: {content}")
			
			except _exception.ZaloLoginError as e:
				raise _exception.ZaloLoginError(str(e))
				
			except Exception as e:
				raise _exception.ZaloLoginError(f"An error occurred while logging in! {str(e)}")
		
		else:
			raise _exception.LoginMethodNotSupport("Login method is not supported yet")
		
	
