import aiohttp

from re_common.baselibrary.tools.all_requests.mrequest import MRequest
from re_common.baselibrary.utils.baseurl import BaseUrl
from re_common.baselibrary.utils.core.bottomutils import aiohttp_try_except
from re_common.baselibrary.utils.core.requests_core import set_proxy, set_proxy_aio


class AioHttpRequest(MRequest):

    def __init__(self, logger=None):
        if logger is None:
            from re_common.baselibrary import MLogger
            logger = MLogger().streamlogger
        super().__init__(logger=logger)
        self.kwargs = {}

    def builder(self):
        if self.refer:
            self.header["refer"] = self.refer
        self.kwargs["headers"] = self.header
        self.kwargs["proxy"] = set_proxy_aio(self.proxies)
        if BaseUrl.urlScheme(self.url) == "https":
            self.kwargs["verify_ssl"] = False
        self.kwargs["timeout"] = self.timeout
        self.kwargs["allow_redirects"] = self.allow_redirects
        self.kwargs["params"] = self.params
        return self

    @aiohttp_try_except
    async def get(self):
        async with aiohttp.ClientSession() as session:
            async with session.get(url=self.url, **self.kwargs) as resp:
                self.resp = resp
                self.status_code = resp.status
                self.html = await resp.text()

    @aiohttp_try_except
    async def post(self):
        async with aiohttp.ClientSession() as session:
            async with session.post(url=self.url, data=self.data, **self.kwargs) as resp:
                self.resp = resp
                self.status_code = resp.status
                self.html = await resp.text()

    def all_middlerwares(self):
        bools, dicts = True, {}
        for item in self.middler_list:
            bools, dicts = item()
            if not bools:
                return bools, dicts
        return bools, dicts

    def run(self, moths="get"):
        self.builder()
        self.on_request_start()
        if moths == MRequest.GET:
            bools, dicts = self.get()
        elif moths == MRequest.POST:
            bools, dicts = self.post()
        else:
            bools, dicts = False, {}
        self.on_request_end()
        if bools:
            return self.all_middlerwares()
        return bools, dicts
