# coding: utf-8

import json
import requests

from hanlder import RequestHandler as BaseRequestHandler
import tornado.web
from tornado.web import authenticated


from ..utils import deal_errors, get_local_time, get_local_time_string
from .forms import BlogWriterForm, BlogCatalogWriterForm

class RequestHandler(BaseRequestHandler):
    def q(self, query_string, query_variables=None,headers=None, api_url=None):

        if not (headers and isinstance(headers, dict)):
            headers = {}

        if query_variables is None:
            query_variables = {}

        sid = self.get_secure_cookie('SID')
        if api_url:
            url = "http://127.0.0.1:3000" + api_url
        else:
            url = "http://127.0.0.1:3000/console/graphql"
        if sid:
            if 'Authorization' not in headers:
                headers['Authorization'] = 'OOC ' + sid.decode()
        s = requests.Session()

        r = s.post(url, json={"query": query_string, "variables": query_variables}, headers=headers)
        return r.json()


class ApiHandler(RequestHandler):

    def post(self, URL):
        body = self.request.body.decode()
        body = json.loads(body)
        # query_string = self.get_argument('query', "")
        query_string = body["query"]
        variables = body.get("variables", None)
        # print("variables==>",variables)
        r = self.q(query_string, variables, api_url=URL)
        self.write(r)

# console 文章部分开始
class ConsoleBlogdexHandler(RequestHandler):
    BLOG_LIST_QUERY = '''
query Blogs(
  $first: Int
  $sort_by: String
  $sort_direction: String
){
  blog{id,...F1}
}
fragment F1 on BlogApi{
  articles(
    first: $first,
    sort_by: $sort_by,
    sort_direction: $sort_direction
  ) {
    edges {
      node {
        id
        title
        body
        body_markup
        updated
        uid
        is_public
        catalog {
            name
        }
      }
    }
    pageInfo {
      hasPreviousPage
      startCursor
      endCursor
      hasNextPage
    }
  }
}'''
    @authenticated
    def get(self):
        # print("current_user=",self.current_user.username)
        bloglist_query_variables = {
                                  "first": 12,
                                  "sort_by": "updated",
                                  "sort_direction": "desc",
                                }
        bloglist_query_variables = json.dumps(bloglist_query_variables)
        r = self.q(self.BLOG_LIST_QUERY, bloglist_query_variables)

        # print("index==>roooo",r)
        blog_list = r.get("data").get("blog").get("articles").get("edges")
        self.render('/blog/console/blog_articles.html', blog_list=blog_list, get_local_time=get_local_time )


class BlogWriterHandler(RequestHandler):

    BLOG_WRITER_QUERY='''
mutation BlogArticleNew(
  $input_0: BlogArticleNewInput!
) {
  blog_article_new(input: $input_0) {
    article {
      id
      title
      abstract
      body
      body_markup
      is_public
      uid
      catalog{
          uid
      }
    }
  }
}'''

    BLOG_CATALOG_LIST_QUERY = '''
query BlogCatalogs{
  blog{id,...F1}
}
fragment F1 on BlogApi{
  catalogs {
        name
        summary
        body_html
        created
        updated
        uid
        public_article_count
        private_article_count
  }
}'''
    def get_catalogs(self):
        r = self.q(self.BLOG_CATALOG_LIST_QUERY)
        catalog_list = r.get("data").get("blog").get("catalogs")
        return catalog_list

    @authenticated
    def get(self):
        form = BlogWriterForm(self)
        catalog_list = self.get_catalogs()
        self.render("blog/console/blog_writer.html", form=form, catalog_list=catalog_list)

    @authenticated
    def post(self):
        form = BlogWriterForm(self)
        catalog_list = self.get_catalogs()
        if not form.validate():
            error = form.errors

            tag_list = []
            tag_uid = form.tags.data.split(",")[::2]
            tag_name = form.tags.data.split(",")[1::2]
            for u,n in zip(tag_uid, tag_name):
                tag_list.append((u,n))

            return self.render("blog/console/blog_writer.html", form=form,
                                catalog_list=catalog_list, error=error,tag_list=tag_list)


        blogwriter_query_variables = {
        "input_0":
          {
            "title": "",
            "clientMutationId": "1",
            "abstract": "",
            "body": "",
            "is_public": False,
            "catalog_uid": "",
            "tags": "",
          }
        }

        blogwriter_query_variables["input_0"]["is_public"] = form.is_public.data
        blogwriter_query_variables["input_0"]["title"] = form.title.data
        blogwriter_query_variables["input_0"]["abstract"] = form.abstract.data
        blogwriter_query_variables["input_0"]["body"] = form.body.data
        blogwriter_query_variables["input_0"]["catalog_uid"] = form.catalog_uid.data
        blogwriter_query_variables["input_0"]["tags"] = form.tags.data.split(",")[::2]
        # print("form.tags.data==>",form.tags.data)

        blogwriter_query_variables = json.dumps(blogwriter_query_variables)
        r = self.q(self.BLOG_WRITER_QUERY, blogwriter_query_variables)
        if r.get("errors"):
            errors = r.get("errors")
            error = deal_errors(errors)

            tag_list = []
            tag_uid = form.tags.data.split(",")[::2]
            tag_name = form.tags.data.split(",")[1::2]
            for u,n in zip(tag_uid, tag_name):
                tag_list.append((u,n))

            self.render("blog/console/blog_writer.html", form=form,
                    catalog_list=catalog_list, error=error, tag_list=tag_list)

        UID = r.get("data").get("blog_article_new").get("article")["uid"]
        self.redirect("/console/blog/article/" + UID)


class BlogShowHandler(RequestHandler):

    BLOG_SHOW_QUERY = '''
query Blog(
  $uid: String!
){
  blog{id,...F1}
}
fragment F1 on BlogApi{
  article: article_u (
    uid: $uid
  ) {
    title
    body: body_html
    is_public
    uid
    catalog {
        name
    }
    tags {
        uid
        name
    }
  }
}
    '''
    @authenticated
    def get(self, UID):
        blogshow_query_variables = {
                                  "uid": UID,
                                }
        blogshow_query_variables = json.dumps(blogshow_query_variables)
        r = self.q(self.BLOG_SHOW_QUERY, blogshow_query_variables)
        # print('r--->',r)
        blog = r.get("data").get("blog").get("article")
        self.render('blog/console/blog_show.html', blog=blog)


class BlogEditHandler(RequestHandler):
    BLOG_EDIT_QUERY = '''
mutation MyMutation(
  $input: BlogArticleEditInput!
) {
  blog_article_edit(input: $input) {
    article {
      id
      title
    }
  }
}'''

    BLOG_SHOW_QUERY = '''
query Blog(
  $uid: String!
){
  blog{id,...F1}
}
fragment F1 on BlogApi{
  article: article_u (
    uid: $uid
  ) {
    title
    body
    abstract
    is_public
    catalog {
        name
        uid
    }
    tags {
        uid
        name
    }
  }
}'''

    BLOG_CATALOG_LIST_QUERY = '''
query BlogCatalogs{
  blog{id,...F1}
}
fragment F1 on BlogApi{
  catalogs {
        name
        summary
        body_html
        created
        updated
        uid
        public_article_count
        private_article_count
  }
}'''
    def get_catalogs(self):
        r = self.q(self.BLOG_CATALOG_LIST_QUERY)
        catalog_list = r.get("data").get("blog").get("catalogs")
        return catalog_list

    @authenticated
    def get(self, UID):
        form = BlogWriterForm(self)
        catalog_list = self.get_catalogs()

        blogshow_query_variables = {
                                  "uid": UID,
                                }
        blogshow_query_variables = json.dumps(blogshow_query_variables)
        r = self.q(self.BLOG_SHOW_QUERY, blogshow_query_variables)
        blog = r.get("data").get("blog").get("article")
        # print("blog==>",blog)

        self.render("blog/console/blog_edit.html",
                    form=form, blog=blog, catalog_list=catalog_list)

    @authenticated
    def post(self, UID):
        form = BlogWriterForm(self)
        catalog_list = self.get_catalogs()
        blogshow_query_variables = {
                                  "uid": UID,
                                }
        r = self.q(self.BLOG_SHOW_QUERY, blogshow_query_variables)
        blog = r.get("data").get("blog").get("article")

        if not form.validate():
            error = form.errors

            # tag_list = []
            # tag_uid = form.tags.data.split(",")[::2]
            # tag_name = form.tags.data.split(",")[1::2]
            # for u,n in zip(tag_uid, tag_name):
            #     tag_list.append((u,n))
            return self.render("blog/console/blog_edit.html",
                                form=form,blog=blog,
                                catalog_list=catalog_list,
                                error = error)

        blogedit_query_variables = {
          "input": {
            "clientMutationId": "1",
            "uid": "",
            "title": "",
            "abstract": "",
            "body": "",
            "is_public": "",
            "catalog_uid": "",
            "tags": ""
          }
        }

        blogedit_query_variables["input"]["is_public"] = form.is_public.data
        blogedit_query_variables["input"]["uid"] = UID
        blogedit_query_variables["input"]["title"] = form.title.data
        blogedit_query_variables["input"]["abstract"] = form.abstract.data
        blogedit_query_variables["input"]["body"] = form.body.data
        blogedit_query_variables["input"]["catalog_uid"] = form.catalog_uid.data
        blogedit_query_variables["input"]["tags"] = form.tags.data.split(",")[::2]


        blogedit_query_variables = json.dumps(blogedit_query_variables)
        r = self.q(self.BLOG_EDIT_QUERY, blogedit_query_variables)

        self.redirect("/console/blog/article/" + UID)


class BlogDelHandler(RequestHandler):

    BLOG_DEL_QUERY  = '''
mutation MyMutaion (
  $input_0: BlogArticleDeleteInput!
) {
  blog_article_delete(input: $input_0) {
    status
    message
  }
}'''

    @authenticated
    def get(self, UID):
        blogdel_query_variables = {
          "input_0": {
            "clientMutationId": "1",
            "uid": ""
          }
        }

        blogdel_query_variables["input_0"]["uid"] = UID
        blogdel_query_variables = json.dumps(blogdel_query_variables)
        r = self.q(self.BLOG_DEL_QUERY, blogdel_query_variables)
        # print("status===>",r)
        status = r.get("data").get("blog_article_delete").get('status')
        self.redirect("/console/blog/article")

# console 文章部分结束

# console 目录部分开始
class BlogCatalogindexHandler(RequestHandler):
    BLOG_CATALOG_LIST_QUERY = '''
query BlogCatalogs{
  blog{id,...F1}
}
fragment F1 on BlogApi{
  catalogs {
        name
        summary
        body_html
        created
        updated
        uid
        public_article_count
        private_article_count
  }
}'''

    @authenticated
    def get(self):
        r = self.q(self.BLOG_CATALOG_LIST_QUERY)

        catalog_list = r.get("data").get("blog").get("catalogs")
        self.render('/blog/console/catalogs.html',
                    catalog_list=catalog_list,
                    get_local_time_string=get_local_time_string )


class BlogCatalogWriterHandler(RequestHandler):
    pass
#
#     BLOG_CATALOG_WRITER_QUERY='''
# mutation BlogCatalogNew(
#   $input_0: BlogCatalogNewInput!
# ) {
#   blog_catalog_new(input: $input_0) {
#     catalog {
#       uid
#       body_html
#       name
#       public_article_count
#       private_article_count
#       created
#       updated
#     }
#   }
# }'''
#
#     @authenticated
#     def get(self):
#         form = BlogCatalogWriterForm(self)
#         self.render("blog/console/catalog_writer.html")
#
#     @authenticated
#     def post(self):
#         form = BlogCatalogWriterForm(self)
#         if not form.validate():
#             error = form.errors
#             # print("error==>",error)
#             return self.render("blog/console/catalog_writer.html",
#                                 form=form, error=error)
#
#         catalogwriter_query_variables = {
#         "input_0":
#             {
#               "clientMutationId": "1",
#             	"name": "",
#                 "summary": "",
#                 "body": "",
#             }
#         }
#
#         catalogwriter_query_variables["input_0"]["name"] = form.name.data
#         catalogwriter_query_variables["input_0"]["summary"] = form.summary.data
#         catalogwriter_query_variables["input_0"]["body"] = form.body.data
#
#         r = self.q(self.BLOG_CATALOG_WRITER_QUERY, catalogwriter_query_variables)
#         # print("r===>",r)
#         if r.get("errors"):
#             errors = r.get("errors")
#             error = deal_errors(errors)
#             self.render("blog/console/catalog_writer.html",
#                                 form=form, error=error)
#
#         UID = r.get("data").get("blog_catalog_new").get("catalog")["uid"]
#         self.redirect("/console/blog/catalog/" + UID)


class BlogCatalogShowHandler(RequestHandler):
    CATALOG_SHOW_QUERY = '''
query BlogCatalog(
  $uid: String!
){
  blog{id,...F1}
}
fragment F1 on BlogApi{
  catalog: catalog_u(
    uid: $uid
  ) {
    body
    name
    summary
    public_article_count
    private_article_count
    created
    updated
    uid
    }

}'''

    @authenticated
    def get(self, UID):
        catalogshow_query_variables = {
                                    "uid": UID,
                                    }
        catalogshow_query_variables = json.dumps(catalogshow_query_variables)
        r = self.q(self.CATALOG_SHOW_QUERY, catalogshow_query_variables)
        catalog = r.get("data").get("blog").get("catalog")
        self.render("blog/console/catalog_show.html", catalog=catalog, get_local_time_string=get_local_time_string )

class BlogCatalogEditHandler(RequestHandler):
    CATALOG_EDIT_QUERY = '''
mutation MyMutation(
  $input: BlogCatalogEditInput!
) {
  blog_catalog_edit(input: $input) {
    catalog {
      id
      uid
      name
    }
  }
}'''

    CATALOG_SHOW_QUERY = '''
query BlogCatalog(
  $uid: String!
){
  blog{id,...F1}
}
fragment F1 on BlogApi{
  catalog: catalog_u(
    uid: $uid
  ) {
    body
    name
    summary
    public_article_count
    private_article_count
    created
    updated
    }

}'''

    @authenticated
    def get(self, UID):
        form = BlogCatalogWriterForm(self)

        catalog_query_variables = {
                                "uid": UID,
                                }

        catalog_query_variables = json.dumps(catalog_query_variables)
        r = self.q(self.CATALOG_SHOW_QUERY, catalog_query_variables)
        catalog = r.get("data").get("blog").get("catalog")

        self.render("blog/console/catalog_edit.html", form=form, catalog=catalog)

    @authenticated
    def post(self, UID):
        form = BlogCatalogWriterForm(self)
        if not form.validate():
            return self.render("blog/console/catalog_edit.html", form=form)

        catalogedit_query_variables = {
            "input": {
                "clientMutationId": "1",
                "uid": "",
                "name": "",
                "summary": "",
                "body": ""
            }
        }
        catalogedit_query_variables["input"]["uid"] = UID
        catalogedit_query_variables["input"]["name"] = form.name.data
        catalogedit_query_variables["input"]["summary"] = form.summary.data
        catalogedit_query_variables["input"]["body"] = form.body.data

        catalogedit_query_variables = json.dumps(catalogedit_query_variables)
        r = self.q(self.CATALOG_EDIT_QUERY, catalogedit_query_variables)
        self.redirect("/console/blog/catalog/" + UID)


class BlogCatalogDelHander(RequestHandler):

    CATA_DEL_QUERY = '''
mutation MyMutation(
  $input: BlogCatalogDeleteInput!
) {
  blog_catalog_delete(input: $input) {
		status
        message
  }
}'''

    @authenticated
    def get(self, UID):
        catalogdel_query_variables = {
            "input": {
                  "clientMutationId": "1",
                  "uid": ""
                	}
        }

        catalogdel_query_variables["input"]["uid"] = UID
        catalogdel_query_variables = json.dumps(catalogdel_query_variables)
        r = self.q(self.CATA_DEL_QUERY, catalogdel_query_variables)
        del_info = r.get("data").get("blog_catalog_delete")
        status = del_info.get("status")
        error = del_info.get("message")

        current_url = self.request.uri
        back_url = "/console/blog/catalog"

        if not status:
            self.render("/error.html", error=error, current_url=current_url,
                        back_url=back_url)

        self.redirect("/console/blog/catalog")

# console 目录部分结束

# console Tag部分开始
class BlogTagindexHandler(RequestHandler):
    BLOG_TAG_LIST_QUERY = '''
query BlogTags(
  $first: Int
  $sort_by: String
  $sort_direction: String
){
  blog{id,...F1}
}
fragment F1 on BlogApi{
  tags(
    first: $first,
    sort_by: $sort_by,
    sort_direction: $sort_direction
  ) {
    edges {
      node {
        id
        name
        summary
        body
        count
        created
        updated
        uid
      }
    }
    pageInfo {
      hasPreviousPage
      startCursor
      endCursor
      hasNextPage
    }
  }
}'''

    @authenticated
    def get(self):
        r = self.q(self.BLOG_TAG_LIST_QUERY)
        tag_list = r.get("data").get("blog").get("tags").get("edges")
        self.render('/blog/console/tags.html',
                    tag_list=tag_list,
                    get_local_time_string=get_local_time_string)


# console Tag部分结束
