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

from vilya.libs import api_errors
from vilya.libs.text import get_mentions_from_text
from vilya.models.project import CodeDoubanProject
from vilya.models.pull import PullRequest, add_pull, merge_pull, close_pull
from vilya.models.ticket import Ticket
from vilya.models.consts import LINECOMMENT_INDEX_EMPTY
from vilya.models.user import User
from vilya.views.api.utils import RestAPIUI, jsonize
from vilya.libs.api_errors import (
    InvalidFieldError, NoPushPermissionError,
    MissingFieldError, NotJSONError, NotFoundError)


class PullUI(RestAPIUI):
    _q_exports = ['files']
    _q_methods = ['get', 'patch']

    def __init__(self, project_id, ticket_id):
        self.project_id = project_id
        self.ticket_id = ticket_id

        self.ticket = Ticket.get_by_projectid_and_ticketnumber(self.project_id,
                                                               self.ticket_id)

        if not self.ticket:
            raise NotFoundError('pull')

        self.pullreq = PullRequest.get_by_proj_and_ticket(
            self.project_id, self.ticket.ticket_number)

    def get(self, request):
        return self.pullreq.as_dict()

    def patch(self, request):
        request.data = request.data or request.form
        action = request.data.get('action')
        if action == 'merge':
            return self.merge(request)
        elif action == 'close':
            return self.close(request)
        elif action == 'comment':
            return self.add_comment(request)
        elif action == 'codereview':
            return self.add_codereview(request)
        elif action:
            raise InvalidFieldError('action')
        else:
            raise MissingFieldError('action')

    def merge(self, request):
        user = request.user
        ticket = self.ticket
        pullreq = self.pullreq
        if pullreq.merged:
            return {'ok': True}
        error = merge_pull(ticket, pullreq, user, '', request)
        if error:
            raise NoPushPermissionError(error)
        return {'ok': True}

    def close(self, request):
        user = request.user
        ticket = self.ticket
        pullreq = self.pullreq