# -*- coding: utf-8 -*-

# Copyright 2015 OpenMarket Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import hashlib
import random
import string
import syutil
from syutil.base64util import encode_base64

from twisted.web.resource import Resource

import json
from sydent.db.invite_tokens import JoinTokenStore
from sydent.db.threepid_associations import GlobalAssociationStore

from sydent.http.servlets import require_args, send_cors


class StoreInviteServlet(Resource):
    def __init__(self, syd):
        self.sydent = syd

    def render_POST(self, request):
        send_cors(request)
        err = require_args(request, ("medium", "address", "room_id", "sender",))
        if err:
            return json.dumps(err)
        medium = request.args["medium"][0]
        address = request.args["address"][0]
        roomId = request.args["room_id"][0]
        sender = request.args["sender"][0]

        globalAssocStore = GlobalAssociationStore(self.sydent)
        mxid = globalAssocStore.getMxid(medium, address)
        if mxid:
            request.setResponseCode(400)
            return json.dumps({
                "errcode": "THREEPID_IN_USE",
                "error": "Binding already known",
                "mxid": mxid,
            })

        token = self._randomString(128)

        JoinTokenStore(self.sydent).storeToken(medium, address, roomId, sender, token)

        pubKey = self.sydent.keyring.ed25519.verify_key
        pubKeyBase64 = encode_base64(pubKey.encode())

        resp = {
            "token": token,
            "public_key": pubKeyBase64,
        }

        return json.dumps(resp)

    def _randomString(self, length):
        return ''.join(random.choice(string.ascii_letters) for _ in xrange(length))

@@ -1746,16 +1746,250 @@
     %7D)%0A%0A
+        if medium != %22email%22:%0A            request.setResponseCode(400)%0A            return json.dumps(%7B%0A                %22errcode%22: %22M_UNRECOGNIZED%22,%0A                %22error%22: %22Didn't understand medium '%25s'%22 %25 (medium,),%0A            %7D)%0A%0A
         
@@ -2317,42 +2317,371 @@
     
-%7D%0A%0A        return json.dumps(resp)
+    %22display_name%22: self.redact(%22address%22),%0A        %7D%0A%0A        return json.dumps(resp)%0A%0A    def redact(self, address):%0A        return %22@%22.join(map(self._redact, address.split(%22@%22, 1)))%0A%0A    def _redact(self, s):%0A        if len(s) %3E 5:%0A            return s%5B:3%5D + %22...%22%0A        elif len(s) %3E 1:%0A            return s%5B0%5D + %22...%22%0A        else:%0A            return %22...%22
 %0A%0A  

Return a redacted display_name along with tokens