import json

import project_sets
from collections import OrderedDict

def get_ld_logo():
    data = {
      "@context": "https://schema.org",
      "@type": "Organization",
      "url": project_sets.domain,
      "logo": project_sets.logo
    }
    return data


def get_ld_company(offices):
    try:
        main_office = offices.get(main_office=True)
    except:
        main_office = offices[0]


    data = {
        "@context": "https://schema.org",
        "@type": "LocalBusiness",
        "logo": project_sets.logo,
    }

    ld_for_main_office = get_ld_office(main_office)
    data.update(ld_for_main_office)


    departments = []
    for office in offices:
        if office == main_office:
            continue

        departments.append(get_ld_office(office))

    # if departments:
    #     data.update({
    #         'department': departments
    #     })

    return json.dumps(data)


def get_ld_office(office):

    try:
        phones = office.phones()
    except:
        phones = []

    if not phones:
        try:
            phones = office.rel_contacts_for_office
        except:
            phones = []

    data = {
        "name": office.name,
    }

    # На каждой странице (с разметкой или без нее) должно присутствовать хотя бы одно изображение. Робот Google выберет лучшее изображение для показа в результатах поиска с учетом соотношения сторон и разрешения.
    # URL изображений должны быть доступны для сканирования и индексирования. Проверить, есть ли у поискового робота Google доступ к URL вашего контента, можно с помощью инструмента, описанного в этой статье.
    # Изображения должны соответствовать размеченному контенту.
    # Допускаются только графические файлы форматов, совместимых с Google Картинками.
    # Предоставьте несколько изображений в высоком разрешении (не менее 50 000 пикселей по произведению ширины и высоты) со следующими соотношениями сторон: 16 × 9, 4 × 3 и 1 × 1.
    data.update({
        "image": [
            project_sets.logo,
        ]
    })

    # data.update({
    #     "@type": "Store",
    # })
    # не обязательно!

    # AnimalShelter
    #     ArchiveOrganization
    # AutomotiveBusiness
    #     ChildCare
    # Dentist
    #     DryCleaningOrLaundry
    # EmergencyService
    #     EmploymentAgency
    # EntertainmentBusiness
    #     FinancialService
    # FoodEstablishment
    #     GovernmentOffice
    # HealthAndBeautyBusiness
    #     HomeAndConstructionBusiness
    # InternetCafe
    #     LegalService
    # Library
    #     LodgingBusiness
    # MedicalBusiness
    #     ProfessionalService
    # RadioStation
    #     RealEstateAgent
    # RecyclingCenter
    #     SelfStorage
    # ShoppingCenter
    #     SportsActivityLocation
    # Store
    #     TelevisionStation
    # TouristInformationCenter
    #     TravelAgency

    i_Dict = {
        "address": {
            "@type": "PostalAddress",
            "streetAddress": office.address,
            "addressLocality": office.city,
            # "addressRegion": "CA",
            # "postalCode": "95129",
            # "addressCountry": "US"
        },
    }
    if phones:
        i_Dict["address"].update({
            "telephone": '{0}{1}'.format(phones[0].prefix, phones[0].nomber_phone),
        })

    data.update(i_Dict)

    gps_longitude = getattr(office, 'gps_longitude', None)
    gps_latitude = getattr(office, 'gps_latitude', None)
    if not gps_longitude:
        gps_longitude = getattr(project_sets, 'gps_longitude', None)
    if not gps_latitude:
        gps_latitude = getattr(project_sets, 'gps_latitude', None)
    if gps_longitude and gps_latitude:
        i_Dict = {
            "geo": {
                "@type": "GeoCoordinates",
                "latitude": gps_latitude,
                "longitude": gps_longitude
            },
        }
        data.update(i_Dict)

    data.update({
        "url": project_sets.domain
    })

    # "foundingDate": "2005-02-07", # дата основания

    company_reference_links = getattr(project_sets, 'company_reference_links')
    if company_reference_links:
        data.update({
            "sameAs": company_reference_links
        })

    priceRange = getattr(office, 'priceRange', '$')
    if priceRange:
        data.update({
            "priceRange": priceRange
        })

    work_time_from = getattr(office, 'work_time_from', None)
    if not work_time_from:
        work_time_from = getattr(project_sets, 'work_time_from', '9:00')
    work_time_to = getattr(office, 'work_time_to', None)
    if not work_time_to:
        work_time_to = getattr(project_sets, 'work_time_to', '18:00')

    i_Dict = {
        "openingHoursSpecification": [
            {
                "@type": "OpeningHoursSpecification",
                "dayOfWeek": [
                    "https://schema.org/Monday",
                    "https://schema.org/Tuesday",
                    "https://schema.org/Wednesday",
                    "https://schema.org/Thursday",
                    "https://schema.org/Friday",
                    # "https://schema.org/Saturday"
                ],
                "opens": work_time_from,
                "closes": work_time_to
            },
            # {
            #     "@type": "OpeningHoursSpecification",
            #     "dayOfWeek": "Sunday",
            #     "opens": "08:00",
            #     "closes": "23:00"
            # }
        ],
    }
    # i_Dict = {
    #     "openingHoursSpecification": [
    #         {
    #             "@type": "OpeningHoursSpecification",
    #             "dayOfWeek": "https://schema.org/Monday",
    #             "opens": work_time_from,
    #             "closes": work_time_to
    #         },
    #         {
    #             "@type": "OpeningHoursSpecification",
    #             "dayOfWeek": "https://schema.org/Tuesday",
    #             "opens": work_time_from,
    #             "closes": work_time_to
    #         },
    #         {
    #             "@type": "OpeningHoursSpecification",
    #             "dayOfWeek": "https://schema.org/Wednesday",
    #             "opens": work_time_from,
    #             "closes": work_time_to
    #         },
    #         {
    #             "@type": "OpeningHoursSpecification",
    #             "dayOfWeek": "https://schema.org/Thursday",
    #             "opens": work_time_from,
    #             "closes": work_time_to
    #         },
    #         {
    #             "@type": "OpeningHoursSpecification",
    #             "dayOfWeek": "https://schema.org/Friday",
    #             "opens": work_time_from,
    #             "closes": work_time_to
    #         },
    #         {
    #             "@type": "OpeningHoursSpecification",
    #             "dayOfWeek": "https://schema.org/Saturday",
    #             "opens": work_time_from,
    #             "closes": work_time_to
    #         },
    #         {
    #             "@type": "OpeningHoursSpecification",
    #             "dayOfWeek": "https://schema.org/Sunday",
    #             "opens": work_time_from,
    #             "closes": work_time_to
    #         },
    #     ],
    # }
    data.update(i_Dict)

    return data


