from .models import *
import os, json
from pathlib import Path

BASE_DIR = Path(__file__).resolve().parent


def create_catalogs():
    file_path = f"{BASE_DIR}/json_data/catalogs.json"

    with open(file_path, "r") as f:
        data = json.load(f)

    catalogs = data["catalogs"]

    print("Looping catalogs from json file")
    mapped_ids = {}
    for catalog in catalogs:
        id = catalog["id"]
        title = catalog["title"]
        link = catalog["link"]
        image_path = catalog["image_path"]

        catalog = Catalogs.objects.create(
            title=title.title().strip(), link=link, image_path=image_path
        )
        mapped_ids[id] = str(catalog.id)

    new_file_path = f"{BASE_DIR}/json_data/mapped_ids/catalogs.json"
    with open(new_file_path, "w") as f:
        json.dump(mapped_ids, f, indent=4)

    print(f"{len(mapped_ids)} catalog/s created successfully")


def create_categories():
    file_path = f"{BASE_DIR}/json_data/categories.json"

    with open(file_path, "r") as f:
        data = json.load(f)

    categories = data["categories"]

    print("Looping categories from json file")
    mapped_ids = {}
    for category in categories:
        id = category["id"]
        main_category_name = category["main_category_name"]
        sub_category_name = category["sub_category_name"]
        link = category["link"]
        is_active = category["is_active"]

        category = Categories.objects.create(
            main_category_name=main_category_name,
            sub_category_name=sub_category_name.title().strip(),
            link=link,
            is_active=is_active,
        )
        mapped_ids[id] = str(category.id)

    new_file_path = f"{BASE_DIR}/json_data/mapped_ids/category.json"
    with open(new_file_path, "w") as f:
        json.dump(mapped_ids, f, indent=4)

    print(f"{len(mapped_ids)} categories created successfully")


def create_news_and_press():
    file_path = f"{BASE_DIR}/json_data/news_and_press.json"

    with open(file_path, "r") as f:
        data = json.load(f)

    medias = data["medias"]

    print("Looping news and press from json file")
    mapped_ids = {
        "news": {},
        "press": {},
    }
    for media in medias:
        id = media["id"]
        title = media["title"]
        short_description = media["short_description"]
        long_description = media["long_description"]
        image_path = media["image_path"]
        link = media["link"]
        type = media["type"]

        media = NewsAndPressReleases.objects.create(
            title=title.title().strip(),
            short_description=short_description,
            long_description=long_description,
            image_path=image_path,
            type=type,
            link=link,
        )

        if type == "news":
            mapped_ids["news"][id] = str(media.id)
        else:
            mapped_ids["press"][id] = str(media.id)

    new_file_path = f"{BASE_DIR}/json_data/mapped_ids/news_and_press.json"
    with open(new_file_path, "w") as f:
        json.dump(mapped_ids, f, indent=4)

    print(f"{len(mapped_ids)} news/press created successfully")


def create_news_gallery():
    file_path = f"{BASE_DIR}/json_data/news_gallery.json"

    with open(file_path, "r") as f:
        data = json.load(f)

    images = data["news_images"]

    with open(f"{BASE_DIR}/json_data/mapped_ids/news_and_press.json", "r") as f2:
        data_2 = json.load(f2)

    news = data_2["news"]
    news_keys = list(news.keys())

    print("Looping news images from json file")
    count = 0
    for image in images:
        news_id = image["news_id"]
        image_path = image["image"]

        if not str(news_id) in news_keys:
            continue

        news_uuid = news[str(news_id)]
        news_obj = NewsAndPressReleases.objects.get(id=news_uuid)

        media = NewsGallery.objects.create(
            news=news_obj,
            image_path=image_path,
        )
        count += 1

    print(f"{count} news gallery created successfully")


def create_series():
    file_path = f"{BASE_DIR}/json_data/series.json"

    with open(file_path, "r") as f:
        data = json.load(f)

    series = data["series"]

    print("Looping series from json file")
    mapped_ids = {}
    for s in series:
        id = s["id"]
        name = s["name"]
        is_active = s["is_active"]

        created_series = Series.objects.create(
            name=name.title().strip(),
            is_active=is_active,
        )
        mapped_ids[id] = str(created_series.id)

    new_file_path = f"{BASE_DIR}/json_data/mapped_ids/series.json"
    with open(new_file_path, "w") as f:
        json.dump(mapped_ids, f, indent=4)

    print(f"{len(mapped_ids)} series created successfully")


def create_products():
    file_path = f"{BASE_DIR}/json_data/products.json"

    with open(file_path, "r") as f:
        data = json.load(f)
    products = data["products"]

    with open(f"{BASE_DIR}/json_data/mapped_ids/series.json", "r") as f:
        series = json.load(f)

    with open(f"{BASE_DIR}/json_data/mapped_ids/category.json", "r") as f:
        categories = json.load(f)

    print("Looping products from json file")
    mapped_ids = {}
    for p in products:
        id = p["id"]
        edp_number = p["edp_number"]
        article_number = p["article_number"]
        description = p["description"]
        name = p["name"]
        finish = p["finish"]
        size = p["size"]
        category_id = p["category_id"]
        price = p["price"]
        is_active = p["is_active"]
        sold_as_set = p["sold_as_set"]
        is_discounted = p["is_discounted"]
        discount_rate = p["discount_rate"]
        discount_valid_until = p["discount_valid_until"]
        quantity = p["quantity"]
        series_id = p["series_id"]
        arrival_date = p["arrival_date"]
        is_best_seller = p["is_best_seller"]
        image_path = p["image_path"]

        series_obj = None
        category_obj = None

        series_objects = Series.objects.filter(id=series[str(series_id)])

        if series_objects.exists():
            series_obj = series_objects.first()

        category_objects = Categories.objects.filter(id=categories[str(category_id)])

        if category_objects.exists():
            category_obj = category_objects.first()

        created_series = Products.objects.create(
            name=name.title().strip(),
            image_path=image_path,
            edp_number=edp_number,
            article_number=article_number,
            description=description,
            finish=finish,
            size=size,
            is_active=is_active,
            price=price,
            sold_as_set=sold_as_set,
            is_discounted=is_discounted,
            discount_rate=discount_rate,
            discount_valid_until=(
                None if discount_valid_until == "None" else discount_valid_until
            ),
            quantity=quantity,
            arrival_date=(None if arrival_date == "None" else arrival_date),
            is_best_seller=is_best_seller,
            category=category_obj,
            series=series_obj,
        )
        mapped_ids[id] = str(created_series.id)

    new_file_path = f"{BASE_DIR}/json_data/mapped_ids/products.json"
    with open(new_file_path, "w") as f:
        json.dump(mapped_ids, f, indent=4)

    print(f"{len(mapped_ids)} products created successfully")


def create_product_gallery():
    file_path = f"{BASE_DIR}/json_data/product_gallery.json"

    with open(file_path, "r") as f:
        data = json.load(f)
    images = data["images"]

    with open(f"{BASE_DIR}/json_data/mapped_ids/products.json", "r") as f:
        products = json.load(f)

    products_keys = list(products.keys())

    print("Looping images from json file")
    count = 0
    for i in images:
        image_path = i["image_path"]
        product_id = i["product_id"]
        is_shown = i["is_shown"]

        if not str(product_id) in products_keys:
            continue

        product_obj = Products.objects.get(id=products[str(product_id)])
        created_series = ProductGallery.objects.create(
            image_path=image_path,
            product=product_obj,
            is_shown=is_shown,
        )

        count += 1

    print(f"{count} product images created successfully")
