"""Add an HTTP header to each response."""
import base64
import json
import subprocess


class AddHeader:
    def __init__(self):
        self.num = 0
    def request(self, flow):
        req = flow.request
        # if req.method == 'GET' and req.path.endswith('comfort'):
        print(req.url)

            # with open('/tmp/body2.txt', 'w') as f:
            #     # print(dir(req.headers))
            #     headers = {i[0]: i[1]for i in req.headers.items()}
            #     print(headers['x-kpsdk-dt'], len(headers['x-kpsdk-dt']))
            #     print(len(req.content))
            #     f.write(json.dumps({
            #         'body': base64.b64encode(req.content).decode(),
            #         'headers': headers
            #     }))
            # p = subprocess.Popen(['/Users/wang/Desktop/node/out/Release/node', '/Users/wang/Documents/mine-vm/xbk.js'],
            # # p = subprocess.Popen(['/Users/wang/Documents/node/nodemacintel', '/Users/wang/Documents/mine-vm/xbk.js'],
            #                      stdin=subprocess.PIPE,
            #                      stdout=subprocess.PIPE,
            #                      stderr=subprocess.PIPE)
            # output, err = p.communicate(timeout=30)
            # print('err', err)
            # print('out', output)
            # # if p.returncode != 0:
            # #     raise Exception("")
            # # input('....')
            # d = json.loads(open('/tmp/body.txt', 'r').read())
            # req.content = base64.b64decode(d['body'].encode())
            # print(d['headers']['x-kpsdk-dt'], len(d['headers']['x-kpsdk-dt']))
            # req.headers.update({
            #     # 'x-kpsdk-dt': d['headers']['x-kpsdk-dt'],
            #     'x-kpsdk-dt': '16gx42ux1d9y73x5gx36z217z0in',
            #     # 'x-kpsdk-ct': d['headers']['x-kpsdk-ct'],
            # })

    def response(self, flow):
        req = flow.request
        res = flow.response

        if req.method == 'GET' and req.path.endswith('comfort'):
            print('res', req.url)
            res.content = open('/Users/wang/Documents/jsvmp/reese84.js','rb').read()
        # if req.path.find('ips.js') > -1:
        #     with open('/Users/wang/Documents/mine-vm/tests/ksada2.js', 'wb') as f:
        #     # with open('/Users/wang/Documents/jsvmp/t.js', 'wb') as f:
        #         f.write(res.content)
        # if req.path.find('/tl') > -1:
        #     d = json.loads(open('/tmp/body3.txt', 'r').read())
        #     res.headers.update({
        #         'x-kpsdk-st': str(d['st']),
        #         'x-kpsdk-ct': d['ct'],
        #         'x-kpsdk-r': str(d['ct']),
        #     })
        #     res.headers.pop('set-cookie')
        #
        #     res.headers.insert(0,'set-cookie', f'ak_bm_vw_1.1-ssn={d["ct"]}; Max-Age=86400; Path=/; Expires=Fri, 16 Aug 2024 10:25:31 GMT; HttpOnly; Secure; SameSite=None')
        #     res.headers.insert(1,'set-cookie', f'ak_bm_vw_1.1={d["ct"]}; Max-Age=86400; Path=/; Expires=Fri, 16 Aug 2024 10:25:31 GMT; HttpOnly; Secure; SameSite=None')




addons = [AddHeader()]