from flask import flash, request, redirect, url_for, Response,Blueprint
from flask_restful import Resource, Api
import requests
from time import sleep
from backstage.utils import translate
from collections import defaultdict
from os import path
from backstage.config import PORTAL_SERVER

contents_app = Blueprint('contents', __name__)
api = Api(contents_app)
TYPE_URL_FOR = {'collection': 'collections.collection_list',
                'blog': 'blogs.blog_list'}

def checktype(articletype):
    if articletype == 'blog':
        return 'blog'
    return articletype

def create_content(data, image_data):
    new_response = requests.post('{}new_content'.format(PORTAL_SERVER), json=data)
    print("Request returned " + str(new_response.status_code))
    if new_response.status_code == 201:
        #flash('新增文章失敗', 'danger')
        return "<script>alert('已有重複的標題，請重新設定');history.go(-1);</script>"
    if new_response.status_code == 200:
        if not image_data == None:
            requests.post(
                '{}upload/static/img?type={}&filename={}'.format(
                    PORTAL_SERVER, checktype(data.get('type')), image_data.filename), files={'image': image_data})
            sleep(1)  # sleep for waiting for new_content API generating content successfully.
        return redirect(url_for('editor.editor', url='/{}/{}'.format(
            checktype(data.get('type')), get_trans_title_url_name(data.get('name')))))
    else:
        flash('新增文章失敗', 'danger')
        print(url_for(TYPE_URL_FOR.get(data.get('type'))))
        return redirect(url_for(TYPE_URL_FOR.get(data.get('type'))))

def create_collection_content(data, img, coverimg, csliderimg, commentimg, ownerimg): #exclusive for collection
    new_response = requests.post('{}new_content'.format(PORTAL_SERVER), json=data)
    if new_response.status_code == 201:
        #flash('新增文章失敗', 'danger')
        return "<script>alert('已有重複的標題，請重新設定');history.go(-1);</script>"
    if new_response.status_code == 200:
        if not img == None:
            requests.post(
                '{}upload/static/img?type={}&filename={}'.format(
                    PORTAL_SERVER, checktype(data.get('type')), img.filename), files={'image': img})
            requests.post(
                '{}upload/static/img?type={}&filename={}'.format(
                    PORTAL_SERVER, checktype(data.get('type')), coverimg.filename), files={'image': coverimg})
            sleep(1)  # sleep for waiting for new_content API generating content successfully.
        if not commentimg == None:
            requests.post(
            '{}upload/img_to_dir?url={}&filename={}'.format(
                PORTAL_SERVER, data.get('dest'), commentimg.filename), files={'image': commentimg})
            sleep(1)
        if not ownerimg == None:
            requests.post(
            '{}upload/img_to_dir?url={}&filename={}'.format(
                PORTAL_SERVER, data.get('dest'), ownerimg.filename), files={'image': ownerimg})
            sleep(1)
            # reserved for slider img wheel
        return redirect(url_for('editor.editor', url='/{}/{}'.format(
            checktype(data.get('type')), get_trans_title_url_name(data.get('name')))))
    else:
        flash('新增文章失敗', 'danger')
        return redirect(url_for(TYPE_URL_FOR.get(data.get('type'))))

def upload_slider_img(data, image_data): #for uploading slider images, currently unused
    if (data.type == 'collection'):
            print("This is a collection article.") #debug use
            if not image_data == None: #just in case
                requests.post(
                '{}upload/static/img/?type={}&filename={}'.format(
                    PORTAL_SERVER, checktype(data.get('type')), image_data.filename), files={'image': data.get('csliderimg')}, type='csliderimg', dest=data.get('dest'))
            sleep(1)  # sleep for waiting for new_content API generating content successfully.


def remove_content():
    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')


def get_trans_title_url_name(title):
    title = title.replace('「','').replace('」','').replace('%','_percent')
    tary = translate(title).replace('$','_').replace('&','_').replace('+','_').replace(',','_').replace('/','_').replace(':','_').replace(';','_').replace('=','_').replace('?','_').replace('@','_').replace(' ','_').replace("'",'_').replace('?','').replace('!','').split('_')
    while("" in tary) :
        tary.remove("")
    return ('_'.join(tary))
    #return translate(title).replace(' ', '_')

def update_manage_table(data, elements, req_args, files, img_type):
    def allow_file(filename):
        return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
    ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif', 'webp'}
    update_data = defaultdict(list)
    for element, value in zip(elements, data):
        if element == 'img':
            value = eval(value)
        elif element == 'yt_video':
            value = {'videoid': str(value)}
        else:
            value = str(value)
        update_data[element].append(value)
    for idx, f_value in enumerate(files):
        if not f_value or f_value.filename == '':
            continue
        if not allow_file(f_value.filename):
            flash('上傳圖片失敗，副檔名必須為:{}'.format(ALLOWED_EXTENSIONS), 'danger')
            continue
        requests.post(
            '{}upload/static/img?type={}&filename={}'.format(
                PORTAL_SERVER, img_type, f_value.filename), files={'image': f_value})
        update_data['img'][idx]['src'] = path.join(
            path.split(update_data['img'][idx]['src'])[0], f_value.filename)
    response = requests.post(
        '{}manages/data?page={}&section={}'.format(
            PORTAL_SERVER, req_args.get('page'), req_args.get('section_class')), json=update_data)
    if response.status_code == 200:
        sleep(1)  # waiting for API upload image successfully.
        flash('修改成功', 'success')
    else:
        flash('修改失敗', 'danger')
