import json
from typing import Union, List, Dict

import pandas as pd

from app.config import logger
from app.convert.base_converter import BaseConverter
from app.convert.utils.content_from_file import content_from_file
from app.convert.utils.convert_encoding_meta import convert_encoding_meta


class FacebookPostsConverter(BaseConverter):
    def read_file(self) -> None:
        json_file = content_from_file(self.content)
        content = convert_encoding_meta(json_file.read())
        self.datadict = json.loads(content)

    def add_metadata(self) -> None:
        self.df = self.df.assign(
            index="facebook_posts",
            type="posts",
            network="Facebook"
        )

    def convert_columns(self) -> None:
        facebook_posts = self.datadict.get('other_photos_v2', [])
        self.df = pd.DataFrame(facebook_posts)
        self.df['creation_timestamp'] = self.df['creation_timestamp'].astype(
            int)

    def rename_columns(self) -> None:
        self.df.rename(columns={
            "description": "content",
            "uri": "chemin"
        }, inplace=True)

    def clean_data(self) -> None:
        self.df['url'] = ""
        self.df.drop(columns=['media_metadata'], errors='ignore', inplace=True)
        self.df.fillna(value="", inplace=True)


def convert_facebook_posts_json(content: Union[str, bytes]) -> List[Dict]:
    logger.info(f"Starting conversion of {len(content)} bytes")
    converter = FacebookPostsConverter(content)

    return converter.convert()
