import base64
import math
import re
from urllib.parse import quote, unquote


def wv(t, e, n, r, o):
    return math.floor(((t - e) / (n - e)) * (o - r) + r)


class PxUtils():
    def __init__(self):
        pass

    def encode_payload(self, payload, uuid, ts=''):
        sts = ts if len(ts) != 0 else '1604064986000'
        t1 = self.ie(payload, 50)
        # print(t1)
        BasePayload = self.encode(t1)
        print(BasePayload)
        fv = self.ie(self.encode(sts), 10)
        print(fv)
        t3 = self.Ev(fv, len(BasePayload), uuid)
        return self.Fa(fv, BasePayload, t3)
    def ie(self, t, e):
        n = bytearray()
        for i in range(len(t)):
            n.append(e ^ ord(t[i]))
        return n.decode()
    def encode(self, t):
        encoded_str = quote(t)
        res = re.findall('(%[0-9A-F]{2})', encoded_str)
        for i in set(list(res)):
            # print(i, '0x'+i[1:])
            encoded_str = encoded_str.replace(i, chr(int('0x'+i[1:] , 16)))
        b64_encoded = base64.b64encode(encoded_str.encode('utf-8')).decode('utf-8')
        return b64_encoded

    def Ev(self, t, e, n):
        r = self.ie(self.encode(n), 10)
        o = []
        a = -1
        for i in range(len(t)):
            l = math.floor(i / len(r)+ 1)
            # print(l)
            if i >= len(r):
                c = i % len(r)
            else:
                c = i
            u = ord(r[c]) * ord(r[l])
            # print(i, l, c, u)
            if u > a:
                a = u
        for f in range(len(t)):
            s = math.floor(f / len(r)) + 1
            d = f % len(r)
            p = ord(r[d]) * ord(r[s])
            # print(f, s, d, p, p > e, wv(p, 0, a, 0, e-1))
            if p >= e:
                p = wv(p, 0,a,0,e-1)
            while p in o:
                p += 1
            o.append(p)

        o = sorted(o)
        return o

    def Fa(self, t, e, n):
        r = ''
        o = 0
        a = t
        for i in range(len(t)):
            print(i,o,n[i], n[i] - i - 1, e[o: n[i] - i - 1], a[i], e[o: n[i] - i - 1]+a[i])
            r += e[o: n[i]-i-i] + a[i]
            o = n[i] - i - 1
        print(e[o:])
        r += e[o:]
        return  r


if __name__ == '__main__':
    p = PxUtils()
    payload = '[{"t":"PX12095","d":{"PX11645":"https://www.flyfrontier.com/","PX12207":0,"PX12458":"MacIntel","PX11902":0,"PX11560":4769,"PX12248":3600,"PX11385":1700553697276,"PX12280":1700553697286,"PX11496":"31fafcb0-8844-11ee-8d49-97ed9bc8f96f","PX12564":null,"PX12565":-1,"PX11379":false}}]'
    uuid = '31fafcb0-8844-11ee-8d49-97ed9bc8f96f'
    print(p.encode_payload(payload, uuid))