from flask import flash, render_template, Blueprint, request, redirect, url_for
from flask.app import Flask
from flask.wrappers import Response
import requests
import os
import fnmatch
import re
import markdown
import uuid
import subprocess
import time
from backstage.blogs.forms import BlogCreateForm
from backstage.utils import get_now_time, translate
from backstage.utils.routes import create_content, remove_content, get_trans_title_url_name
from backstage.config import PORTAL_SERVER, UPLOAD_PATH_MAP, BHOUSE_WEB_DIR
from bs4 import BeautifulSoup

blogs_app = Blueprint('blogs', __name__)

SwfType = {
   "other_furniture": "other_furniture",
   "sofa":"sofa",
    "cabinet":"cabinet",
    "desk":"desk",
    "dining_chair":"dining_chair",
    "dining_table":"dining_table",
    "mattress":"mattress",
    "side_cabinet":"side_cabinet",
    "side_table":"side_table",
     "wardrobe":"wardrobe",
}
SfType = {
    "custom_made_system_cabinet": "客製模組系統櫃",
    "system_cabinet": "模組系統櫃單品",
}

#furniturePath = UPLOAD_PATH_MAP[0][0] + '../設計家具'
furniturePath = BHOUSE_WEB_DIR + '/content/furniture_design_list'
sfurniturePath = UPLOAD_PATH_MAP[0][0] + '../模組系統櫃'
furnitureTypes = []
furnitureTypeFiles = []
furnitureFiles = []
furnitures = []


def refreshFur(itype):
    scanpath = ""
    furnitureTypes.clear()
    furnitureTypeFiles.clear()
    furnitureFiles.clear()
    furnitures.clear()
    if itype == '單品家具':
        scanpath = furniturePath
    else:
        scanpath = sfurniturePath
    print(scanpath)
    for dirname, dirnames, filenames in os.walk(scanpath):
        # print path to all subdirectories first.
        for subdirname in dirnames:
            if subdirname.find('.') == -1:
                furnitureTypes.append(subdirname)

        # print path to all filenames.
        for filename in filenames:
            if filename.find('_index.md') >= 0:
                furnitureTypeFiles.append(os.path.join(dirname, filename))
            if filename.find('index.md') >= 0:
                furnitureFiles.append(os.path.join(dirname, filename))

    headerStart = False
    for files in furnitureFiles:
        tmpfurniture = {}
        typeFlag = 0 #if type does not exist flag will not be triggered
        with open(files, 'r', encoding="utf-8") as md:
            md_line_data = md.readlines()
            # print(md_line_data)
        for line in md_line_data:
            # print(line)
            if '---' in line:
                headerStart = not headerStart
                continue
            if headerStart:
                if 'title:' in line:
                    tmpfurniture['title'] = re.split('"|\n', line)[1]
                if 'date:' in line:
                    tmpfurniture['date'] = re.split(':"|\n', line)[0][6:]
                if 'draft:' in line:
                    tmpfurniture['draft'] = re.split(':"|\n', line)[0][7:]
                if 'type:' in line:
                    typeFlag = 1
                    tmpfurniture['type'] = re.split('"|\n', line)[1]
                if 'url:' in line:
                    tmpfurniture['url'] = re.split('"|\n', line)[1]
                if 'image:' in line:
                    tmpfurniture['image'] = re.split('"|\n', line)[1]
                if 'tags:' in line:
                    tmpfurniture['tags'] = re.split('"|\n', line)[1]
        # 避免加入類別項目
        if typeFlag == 0:
            furnitures.append(tmpfurniture)
        elif tmpfurniture['type'] != tmpfurniture['url'][1:]:
            furnitures.append(tmpfurniture)


def newFur(irequest):
    # print(irequest.url)
    myType = {}
    myPath = ""
    # print(str(irequest.url).find("system_furniture"))
    if str(irequest.url).find("system_furniture") >= 0:
        myType = SfType
        myPath = sfurniturePath
    else:
        myType = SwfType
        myPath = furniturePath
    ename = get_trans_title_url_name(irequest.args['newSwfName'])
    front_matter = '''---
meta_title: "{}"\n
meta_description: "{}"\n
title: "{}"\n
date: {}\n
draft: true\n
type: "{}"\n
url: "/furniture_design/{}/{}"\n
image: ""\n
---'''.format(irequest.args['newSwfName'], '', irequest.args['newSwfName'], get_now_time(), irequest.args['newSwfDropdown'], irequest.args['newSwfDropdown'], ename)

    newPath = myPath + '/' + myType[irequest.args['newSwfDropdown']] + '/' + ename
    if not os.path.exists(newPath):
        os.mkdir(newPath)
    newPath = newPath 
    with open(os.path.join(newPath, 'index.md'), 'w', encoding="utf-8") as md:
        md.write(front_matter)

    # furniturePath
    # get_trans_title_url_name()
    return furniturePath

@blogs_app.route('/backstage/update', methods=['GET'])
def update():
    subprocess.run(["cp -r /var/www/bhouse2 /var/www/bhousebackup"], shell=True)
    subprocess.run(["cd /var/www/bhouse2/New-Bhouse-Web; hugo"], shell=True)
    time.sleep(5)
    subprocess.run(["rsync -azv -e ssh /var/www/bhouse2/New-Bhouse-Web/public root@172.105.241.163:/var/www/New-Bhouse-Web"], shell=True) # remove n before handing to customer
    return redirect(url_for('blogs.blog_list'))

@blogs_app.route('/backstage/blogs', methods=['GET'])
def blog_list():
    response = requests.get('{}contents?url=/blog'.format(PORTAL_SERVER))
    #print('{}contents?url=/blog'.format(PORTAL_SERVER))
    if response.status_code == 200:
        sortedData = sorted(response.json(), key=lambda x: x['date'], reverse=True)
        return render_template('blogs.html',
                               title='設計專欄',
                               legend='設計專欄列表',
                               blogs=sortedData,
                               length=len(response.json()),
                               form=BlogCreateForm())


@blogs_app.route('/backstage/new_solid_wood_furniture', methods=['GET'])
def new_solid_wood_furniture():
    # edit_solid_wood_furniture()
    return newFur(request)


@blogs_app.route('/backstage/new_system_furniture', methods=['GET'])
def new_system_furniture():
    # edit_solid_wood_furniture()
    return newFur(request)


@blogs_app.route('/backstage/del_solid_wood_furniture', methods=['GET'])
def del_solid_wood_furniture():
    url = request.args.get('url', type=str)
    response = requests.delete('{}contents?url={}'.format(PORTAL_SERVER, url))
    if response.status_code == 200:
        flash('刪除文章成功', 'success')
    else:
        flash('刪除文章失敗', 'danger')
    # edit_solid_wood_furniture()
    return url


@blogs_app.route('/backstage/edit_solid_wood_furniture', methods=['GET'])
def edit_solid_wood_furniture():
    response = requests.get('{}contents?url=/furniture_design'.format(PORTAL_SERVER))
    #print('{}contents?url=/maincategories'.format(PORTAL_SERVER))
    if response.status_code == 200:
        #sortedData = sorted(response.json(), key=lambda x: x['date'], reverse=True)
        return render_template('solid_wood_furniture.html',
                               title='單品家具',
                               legend='單品家具',
                               furnitures=response.json(),
                               length=len(response.json()))


'''
def edit_solid_wood_furniture():
    refreshFur('單品家具')
    sortedData = sorted(furnitures, key=lambda x: x['date'], reverse=True)
    sortedData = sorted(sortedData, key=lambda x: x['type'])
    sortedData = furnitures
    return render_template('solid_wood_furniture.html',
                           title='單品家具',
                           legend='單品家具',
                           furnitures=sortedData, length=len(furnitures),
                           )
'''

@blogs_app.route('/backstage/edit_system_furniture', methods=['GET'])
def edit_system_furniture():
    refreshFur('模組系統櫃')
    sortedData = sorted(furnitures, key=lambda x: x['date'], reverse=True)
    sortedData = sorted(sortedData, key=lambda x: x['type'])
    return render_template('system_furniture.html',
                           title='模組系統櫃',
                           legend='模組系統櫃',
                           furnitures=sortedData, length=len(furnitures),
                           )


@blogs_app.route('/backstage/edit_news', methods=['GET'])
def edit_news():
    response = requests.get('{}contents?url=/news'.format(PORTAL_SERVER))
    if response.status_code == 200:
        #sortedData = sorted(response.json(), key=lambda x: x['date'], reverse=True)
        return render_template('news.html',
                               title='消息與報導',
                               legend='消息與報導',
                               news=response.json(), length=len(response.json()), form=BlogCreateForm()
                               )


@blogs_app.route('/backstage/edit_contact_us', methods=['GET'])
def edit_contact_us():
        return render_template('contact_us.html',
                               title='聯絡我們',
                               )

@blogs_app.route('/backstage/edit_further', methods=['GET'])
def edit_further():
        return render_template('further.html',
                               title='編輯延伸閱讀',
                               )

@blogs_app.route('/backstage/edit_faq', methods=['GET'])
def edit_faq():
    return render_template('frequently_asked_questions.html',
                            title='常見問題',
                            )

@blogs_app.route('/backstage/edit_contact_us_getemail', methods=['GET'])
def edit_contact_us_getemail():
    txt = ""
    newEmail = request.args.get('newemail', type=str)
    footerpath = BHOUSE_WEB_DIR + "/themes/hugo-universal-theme-master/layouts/partials/footer.html"
    with open(footerpath, encoding="utf-8") as inf:
        txt = inf.read()

    result = txt[txt.find('"mailto:')+8:txt.find('"',txt.find('"mailto:')+1)]

    #sortedData = sorted(sortedData, key=lambda x: x['type'])
    return result

@blogs_app.route('/backstage/edit_contact_us_editemail', methods=['GET'])
def edit_contact_us_editemail():
    txt = ""
    newEmail = request.args.get('newemail', type=str)
    footerpath = BHOUSE_WEB_DIR + "/themes/hugo-universal-theme-master/layouts/partials/footer.html"
    with open(footerpath, encoding="utf-8") as inf:
        txt = inf.read()

    result = re.sub(r'"mailto:(\S*)"', '"mailto:' + newEmail + '"', txt)

    with open(footerpath, 'w' , encoding="utf-8") as inf:
        inf.write(result)      

    #sortedData = sorted(sortedData, key=lambda x: x['type'])
    return "{success: Success " + result + "}"

@blogs_app.route('/backstage/blog/create/', methods=['POST'])
def create():
    transcat = ""
    form = BlogCreateForm()
    if form.categories.data == "居家美學":
        transcat = "home_aesthetics"
    elif form.categories.data == "規劃師QA":
        transcat = "room_planner_expertise"
    elif form.categories.data == "驗屋知識":
        transcat = "home_inspection_knowledge"
    else:
        transcat = get_trans_title_url_name(form.categories.data)
    transtitle = get_trans_title_url_name(form.title.data)
    
    form.image.data.filename = str(uuid.uuid4()).replace('-','') + ".webp"

    front_matter = '''---
meta_title: "{}"\n\
meta_description: "{}"\n\
title: "{}"\n\
date: {}\n\
draft: {}\n\
type: "{}"\n\
url: "{}"\n\
image: "/img/title/{}"\n\
categories: "{}"\n\
col1: "{}"\n\
col2: "{}"\n\
introduction: "{}"\n\
question_box_intro: "{}"\n\
readmore_ttl: ["","","","",""]\n\
readmore_lnk: ["","","","",""]\n\
---'''.format(form.title.data, "", form.title.data,
              get_now_time(),
              'true',
              'blog',
              '/blog/{}'.format(transtitle),
              form.image.data.filename,
              form.categories.data,
              transcat, "", "", "")
    data = {'frontMatter': front_matter,
            'name': transtitle,
            'type': 'blog',
            'categories': form.categories.data,
            # 'caturl': caturl
            }

    return create_content(data, form.image.data)

@blogs_app.route('/backstage/edit_blog_getfurther', methods=['GET'])
def edit_blog_getfurther():
    txt = ""
    datapath = BHOUSE_WEB_DIR + "/themes/hugo-universal-theme-master/layouts/partials/further.html"
    data=[]
    with open(datapath, encoding="utf-8") as inf:
        obj=BeautifulSoup(inf, 'html.parser', from_encoding="utf+8").find_all("a")
        for item in obj:
            data.append([item.get('href'), item.text])

    #sortedData = sorted(sortedData, key=lambda x: x['type'])
    return {"data": data}

@blogs_app.route('/backstage/getarticle', methods=['GET'])
def article():
    try:
        response = requests.get('{}contents?url={}'.format(PORTAL_SERVER, "/blog/check_in/"))
        #print('{}contents?url=/blog'.format(PORTAL_SERVER))
        x = response.json()
        return x[0]['title']
    except:
        return "undefined article"

@blogs_app.route('/backstage/edit_blog_editfurther', methods=['GET'])
def edit_blog_editfurther():
    txt = ""
    data=[]
    data.append(request.args.get('data01', type=str))
    data.append(request.args.get('data11', type=str))
    data.append(request.args.get('data21', type=str))
    data.append(request.args.get('data31', type=str))
    data.append(request.args.get('data41', type=str))

    print(data)

    res=[]

    for d in data:
        if d!='':
            try:
                link=d.split("1313")[1]
                if link[-1] == "/":
                    link = link[:-1]
                    d = d[:-1]
                print(link)
                response = requests.get('{}contents?url={}'.format(PORTAL_SERVER, link))
                x = response.json()
                #print('{}contents?url=/blog'.format(PORTAL_SERVER))
                resp = x[0]['title']
                print(resp)
                res.append([resp, d])
            except:
                res.append(["undefined_article", d])
        else:
            res.append(["", ""])
        
    print(res)

    #sortedData = sorted(sortedData, key=lambda x: x['type'])
    return {"data": res}

@blogs_app.route('/backstage/blog/createCat/', methods=['GET'])
def createCat():
    #title = ""
    front_matter = '''---
title: "{}"\n\
date: {}\n\
draft: {}\n\
type: "{}"\n\
categories: "{}"\n\
---'''.format(request.args["title"],
              get_now_time(),
              'false',
              'blog',
              get_trans_title_url_name(request.args["title"]))

    CatPath = UPLOAD_PATH_MAP[0][0]+"../blog/" + get_trans_title_url_name(request.args["title"])

    # print(CatPath)
    if not os.path.exists(CatPath):
        os.mkdir(CatPath)
    with open(os.path.join(CatPath, 'category.md'), 'w', encoding="utf-8") as md:
        md.write(front_matter)

    print("11")
    return Response("你好", 200)


@blogs_app.route('/backstage/news/create/', methods=['POST'])
def createNews():
    form = BlogCreateForm()
    transtitle = get_trans_title_url_name(form.title.data)

    front_matter = '''---
meta_title: "{}"\n
meta_description: "{}"\n
title: "{}"\n\
date: {}\n\
draft: {}\n\
display: {}\n\
type: "{}"\n\
url: "{}"\n\
image: ""\n\
---'''.format(form.title.data, '', form.title.data,
              get_now_time(),
              'true',
              'false',
              'news',
              '/news/{}'.format(transtitle))

    data = {'frontMatter': front_matter,
            'name': transtitle,
            'type': 'news',
            }

    return create_content(data, form.image.data)


@blogs_app.route('/backstage/blog/remove', methods=['POST'])
def remove():
    remove_content()
    return redirect(url_for('blogs.blog_list'))


@blogs_app.route('/backstage/news/remove', methods=['POST'])
def removeNews():
    remove_content()
    return redirect(url_for('blogs.edit_news'))


@blogs_app.route('/backstage/utils', methods=['GET'])
def transService():
    # print(request.args["trantext"])
    return get_trans_title_url_name(request.args["trantext"])


""" def GetCategories():
    GetCategories
    configfiles = [os.path.join(dirpath, f)
        for dirpath, dirnames, files in os.walk(UPLOAD_PATH_MAP+'../blog')
        for f in fnmatch.filter(files, 'category.md')]

    return configfiles """
