from flask import render_template, Blueprint, request, redirect, url_for, flash
import requests
from os import path
from time import sleep
from backstage.utils import translate
from backstage.config import PORTAL_SERVER
from backstage.utils.routes import remove_content
from backstage.config import BHOUSE_SERVER

store_locations_app = Blueprint('store_locations', __name__)


@store_locations_app.route('/backstage/store_location')
def main():
    response = requests.get('{}store_locations'.format(PORTAL_SERVER))
    return render_template('store_location.html',
                           title='門市據點',
                           page='store_location',
                           stores_data=response.json(),
                           bhouse_server=BHOUSE_SERVER)


@store_locations_app.route('/backstage/store_locations/create', methods=['POST'])
def create():
    def get_imgs():
        imgs = []
        for img_src in request.form.getlist('img-{}'.format(idx)):
            imgs.append(img_src)
        for f_img in request.files.getlist('image-{}'.format(idx)):
            img_src = '/img/{}/{}'.format(type_, f_img.filename)
            requests.post('{}statics/img?type={}&filename={}'.format(
                PORTAL_SERVER, type_, f_img.filename), files={'image': f_img})
            imgs.append(img_src)
        return imgs

    def get_district_name():
        return translate(title.replace('門市', '')).lower().replace(' ', '_')

    result = []
    idx = 1
    for title, type_, store, hour, phone, location, parking in zip(
        request.form.getlist('title'), request.form.getlist('type'), request.form.getlist('store'),
        request.form.getlist('hour'), request.form.getlist('phone'),
        request.form.getlist('location'), request.form.getlist('parking')
    ):
        result.append({
            'title': title, 'type': type_, 'imgs': list(get_imgs()), 'store': store,
            'hour': hour, 'phone': phone, 'location': location, 'parking': parking,
            'url': '/{}/bhouse_store_in_{}_city'.format(type_, get_district_name())
        })
        idx += 1
    response = requests.post('{}store_locations'.format(PORTAL_SERVER), json=result)
    if response.status_code == 200:
        sleep(1)  # waiting for API upload image successfully.
        flash('提交成功', 'success')
    else:
        flash('提交失敗', 'danger')
    return redirect(url_for('store_locations.main'))


@store_locations_app.route('/backstage/store_locations/remove_img', methods=['GET'])
def remove_img():
    response = requests.delete('{}statics/img?type={}&filename={}'.format(
        PORTAL_SERVER, request.args.get('type'), path.basename(request.args.get('src'))))
    if response.status_code == 200:
        flash('移除照片成功', 'success')
    else:
        flash('移除照片失敗', 'danger')
    return redirect(url_for('store_locations.main'))


@store_locations_app.route('/backstage/store_locations/remove', methods=['POST'])
def remove():
    remove_content()
    return redirect(url_for('store_locations.main'))
