from flask import request, Blueprint
from flask_restful import Resource, Api
import logging
from bs4 import BeautifulSoup
from models.config import HOMEPAGE_DIR, ROOM_PLANNER_DIR
from models.utils.parsers import get_section_parser, SectionParser
from models.utils.validators import is_valid_section
from models.utils import read_line_md, write_md

manages_app = Blueprint('manages', __name__)
api = Api(manages_app)
logger = logging.getLogger(__name__)
DIR = {'home': HOMEPAGE_DIR, 'room_planner': ROOM_PLANNER_DIR}


class RequiredData():
    def __init__(self):
        self.is_amp_img, self.is_amp_youtube = False, False

    def load(self, section_data, text):
        if '<b' in text:
            soup = BeautifulSoup(text, "html.parser")
            section_data.setdefault('b', []).append(soup.b.string)
        elif '<a ' in text and '</a>' in text:
            soup = BeautifulSoup(text, "html.parser")
            section_data.setdefault('a', []).append(soup.a.string)
        elif '<p' in text:
            soup = BeautifulSoup(text, "html.parser")
            section_data.setdefault('p', []).append(soup.p.string)
        elif '<amp-img' in text:
            self.is_amp_img = True
        elif '<amp-youtube' in text:
            self.is_amp_youtube = True
        elif 'card-text' in text:
            soup = BeautifulSoup(text, "html.parser")
            section_data.setdefault('card_text', []).append(soup.div.string)
        elif 'title mb' in text:
            soup = BeautifulSoup(text, "html.parser")
            section_data.setdefault('title_mb_text', []).append(soup.div.string)
        if self.is_amp_img:
            if 'src' in text:
                src = text.split('src=')[-1].replace('"', '').replace('\n', '')
                section_data.setdefault('img', []).append({'src': src})
            if '</amp-img' in text:
                self.is_amp_img = False
        elif self.is_amp_youtube:
            if 'data-videoid' in text:
                videoid = text.split('data-videoid')[-1].replace('"', '').replace('\n', '')
                section_data.setdefault('yt_video', []).append({'videoid': videoid})
            if '</amp-youtube' in text:
                self.is_amp_youtube = False


class ManageData(Resource):
    def get(self):
        result = []
        require_data = RequiredData()
        for line in read_line_md(DIR.get(request.args.get('page', type=str), [])):
            if '<section' in line:
                soup = BeautifulSoup(line, "html.parser")
                section_class = '_'.join(soup.find_all(class_=True)[0]['class'])
                result.append({'sectionClass': section_class})
            elif not result:
                # for skip the line before fist section
                continue
            else:
                require_data.load(result[-1], line)
        return result

    def post(self):
        is_target_class_section = False
        content = ''
        section_parser = SectionParser(request.json)
        for line in read_line_md(DIR.get(request.args.get('page', type=str), [])):
            if is_target_class_section:
                if '</section>' in line:
                    is_target_class_section = False
                content = section_parser.update(content, line)
            else:
                content += line
            if is_valid_section(request.args.get('section', type=str), line):
                is_target_class_section = True
                section_parser = get_section_parser(
                    request.args.get('section', type=str))(request.json)
        write_md(DIR.get(request.args.get('page', type=str)), content)
        return {'content': content}


api.add_resource(ManageData, '/api/manages/data')
