# -*- coding: UTF-8 -*-
# 作者：huanhuilong
# 标题：Python Web 服务模拟器
# 描述：模拟一个 Web 服务，创建资源，删除一个符合条件的资源，总数应该为0

from error_code import ErrorCode
from store import Store
from router import Router
from validator import KeyValueValidator

import json
import logging
import traceback
logger = logging.getLogger(__name__)


class App:
    def __init__(self) -> None:
        self.store = Store({})
        self.validator = KeyValueValidator()
        self.router = Router({
            '/': self.__home,
            '/kv/create': self.__create,
            '/kv/remove': self.__remove,
            '/kv/count': self.__count,
        })

    def post(self, path, data):
        http_request = {
            'path': path,
            'data': data
        }
        ret, status_code = self.router.dispatch(json.dumps(http_request))
        ErrorCode.internal_ret_2_http(ret)
        resp = ""
        try:
            resp = json.dumps(ret)
        except Exception as e:
            logger.error("parse resp exception:%s", str(e))
            logger.error(traceback.format_exc())

        return resp, status_code

    def __home(self, req):
        return {'err': ErrorCode.SUCCESS, 'result': "Welcome!"}

    def __create(self, req):
        ret = self.validator.validate(req, ['key', 'value'])
        if ret['err'] != ErrorCode.SUCCESS:
            return ret

        return self.store.create(req['key'], req['value'])

    def __remove(self, req):
        ret = self.validator.validate(req, ['key', 'condition'])
        if ret['err'] != ErrorCode.SUCCESS:
            return ret

        return self.store.remove(req['key'], req['condition'])

    def __count(self, req):
        return self.store.count()


if __name__ == '__main__':
    app = App()

    resp, status = app.post('/kv/create', {
        'key': 'test',
        'value': 1000,
    })

    resp, status = app.post('/kv/remove', {
        'key': 'test',
        'condition': 1000,
    })

    resp, status = app.post('/kv/count', {})

    assert status == 200
    assert json.loads(resp)['err'] == 'success'
    assert json.loads(resp)['result'] == 0
