import logging
import os

from django.conf import settings
from django.core.management.base import BaseCommand

from companies.models import Company
from products.models import Product

from utils.woocommerce import migrate_shop_products

import dotenv

dotenv.read_dotenv(
    dotenv=os.path.join(settings.BASE_DIR, '../.env'),
    override=True
    )

logging.basicConfig(
    filename='logs/addtestdata.log',
    filemode='w',
    format='%(levelname)s:%(message)s',
    level=logging.INFO,
    )


class Command(BaseCommand):

    url = "https://woo.enreda.coop/"
    help = 'Load data from example site https://woo.enreda.coop/ '

    def handle(self, *args, **kwargs):
        print("Migrate data from Enreda WooCommerce...\n")
        # find or create company instance
        enreda, created = Company.objects.get_or_create(company_name='enreda', web_link=self.url)
        # set credentials
        credentials = {
            'key': os.getenv('WC_KEY'),
            'secret': os.getenv('WC_SECRET')
        }
        enreda.credentials = credentials
        enreda.save()
        # migrate shop
        print(f"Starting migration...")
        products_created = migrate_shop_products(self.url, credentials['key'], credentials['secret'] )
        print(f"Products created: {len(products_created)}")
