from flask import request, Blueprint
from flask_restful import Resource, Api
from os import path, makedirs
import logging
from bs4 import BeautifulSoup
from models.config import CONTENT_DIR
from models.utils import read_line_md, gen_md_file_dirs, translate, get_now_time
from models.store_locations.templates import store_location_template, amp_img_template
from models.store_locations import STORE_CONTENT_DIR
from models.statics.routes import get_static_imgs_src


store_locations_app = Blueprint('store_locations', __name__)
logger = logging.getLogger(__name__)
api = Api(store_locations_app)


class StoreLocations(Resource):
    def __init__(self):
        self.exist_img_file_src = []

    def get_file_data(self, f_dir):
        result = {}
        is_amp_img = False
        for line in read_line_md(f_dir):
            if 'title: ' in line:
                result['title'] = line.split('title: ')[-1].replace('"', '').replace('\n', '')
            elif 'type: ' in line:
                result['type'] = line.split('type: ')[-1].replace('"', '').replace('\n', '')
            elif 'url: ' in line:
                result['url'] = line.split('url: ')[-1].replace('"', '').replace('\n', '')
            elif '<amp-img' in line:
                is_amp_img = True
            elif 'h2 class="mb-4"' in line:
                result['store'] = BeautifulSoup(line, 'html.parser').h2.string
            elif '營業時間 | ' in line:
                result['hour'] = line.split('營業時間 | ')[-1].replace('\n', '')
            elif '門市電話 | ' in line:
                result['phone'] = BeautifulSoup(line, 'html.parser').a.string
            elif '門市地點 | ' in line:
                result['location'] = BeautifulSoup(line, 'html.parser').a.string
            elif '停車資訊 | ' in line:
                result['parking'] = line.split('停車資訊 | ')[-1].replace('\n', '')
            if is_amp_img:
                if 'src=' in line:
                    img_src = line.split('src=')[-1].replace('"', '').replace('\n', '')
                    if img_src in self.exist_img_file_src:
                        result.setdefault('imgs', []).append(img_src)
                if '</amp-img':
                    is_amp_img = False
        return result

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

    def _get_amp_img_md(self, imgs, title):
        result = ''
        for img_src in imgs:
            amp_img_md = amp_img_template.format(src=img_src, title=title)
            result += amp_img_md + '\n'
        return result

    def get(self):
        result = {}
        for zone, dir_ in STORE_CONTENT_DIR.items():
            self.exist_img_file_src = get_static_imgs_src('store_{}'.format(zone))
            for f_dir in gen_md_file_dirs(dir_):
                result.setdefault(zone, []).append(self.get_file_data(f_dir))
        return result

    def post(self):
        def get_store_dir():
            DISTRICT_STORES = {'store_north': '北部門市',
                               'store_central': '中部門市',
                               'store_south': '南部門市',
                               'store_east': '東部門市'}
            return path.join(CONTENT_DIR,
                             store_data.get('type'),
                             DISTRICT_STORES.get(store_data.get('type'), '中部門市'),
                             store_data.get('title').replace('門市', ''))

        update_md = []
        for store_data in request.json:
            store_location_md = store_location_template.format(
                title=store_data.get('title'),
                date=get_now_time(),
                type=store_data.get('type'),
                url=store_data.get('url'),
                amp_imgs=self._get_amp_img_md(store_data.get('imgs'), store_data.get('title')),
                store=store_data.get('store'),
                hour=store_data.get('hour'),
                phone_without_dash=store_data.get('phone').replace('-', ''),
                phone=store_data.get('phone'),
                location=store_data.get('location'),
                parking=store_data.get('parking'))
            store_dir = get_store_dir()
            makedirs(store_dir, exist_ok=True)
            with open(path.join(store_dir, 'index.md'), 'w', encoding="utf-8") as md:
                md.write(store_location_md)
            update_md.append(store_location_md)
        return update_md


api.add_resource(StoreLocations, '/api/store_locations')
